package cn.fl.project.controller;

import cmm.comm.facade.upload.condition.SysUlDatCfgQueryCondition;
import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.comm.facade.upload.constant.UploadConstant;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.user.facade.system.api.ISysUsrApiService;
import cmm.user.facade.system.condition.SysUsrQueryCondition;
import cmm.user.facade.system.dto.SysUsrDTO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.logger.eum.LogExceptionEnum;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.capital.condition.CapPayInfoQueryCondition;
import cn.fl.capital.dto.CapPayInfoDTO;
import cn.fl.capital.service.ICapPayInfoApiService;
import cn.fl.changeapply.api.IPrjPrdChangeApplyApiService;
import cn.fl.changeapply.condition.PrjPrdChangeApplyQC;
import cn.fl.changeapply.constant.PrjPrdChangeApplyConstant;
import cn.fl.changeapply.dto.PrjPrdChangeApplyDTO;
import cn.fl.changeapply.service.IPrjPrdChangeApplyService;
import cn.fl.changeapply.vo.PrjPrdChangeApplyVO;
import cn.fl.commons.result.ResponseData;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.deviceinfo.api.IDeviceInfoApiService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.handler.ResponseFilter;
import cn.fl.preloan.IPrjPrdDtlGpsApiService;
import cn.fl.preloan.condition.PrjPrdDtlGpsQueryCondition;
import cn.fl.preloan.condition.PrjPrdVehInfoQueryCondition;
import cn.fl.preloan.dto.gps.GpsDeviceDTO;
import cn.fl.prjprddtlgps.dto.PrjPrdDtlGpsDTO;
import cn.fl.prjprddtlgps.service.IPrjPrdDtlGpsService;
import cn.fl.prjprddtlgps.vo.GpsAddressVO;
import cn.fl.prjprddtlgps.vo.PrjPrdDtlGpsVO;
import cn.fl.project.api.ICheckInvoiceApiService;
import cn.fl.project.api.IPrjPrdExtApiService;
import cn.fl.project.api.IPrjPrdGpsApplyApiService;
import cn.fl.project.condition.InvoiceOrCertQueryCondition;
import cn.fl.project.condition.PrjFlowUserInfoQC;
import cn.fl.project.condition.PrjPrdDtlQueryCondition;
import cn.fl.project.constant.CarStyleConstant;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.constant.PrjPrdBscInfoConstant;
import cn.fl.project.dto.CheckInvoiceResultDTO;
import cn.fl.project.dto.PrjPrdExtDTO;
import cn.fl.project.dto.PrjPrdGpsApplyDTO;
import cn.fl.project.service.*;
import cn.fl.project.vo.*;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlDatCfgService;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.vo.SysUlDatCfgDtlVO;
import cn.fl.system.vo.SysUlDatCfgVO;
import cn.fl.system.vo.SysUlFilesRecVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import fl.flow.facade.flow.constant.FlowConstant;
import net.sf.json.JSONArray;
import net.sf.json.util.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @Description: 实际车辆明细信息表 控制层
 */
@Controller
@RequestMapping("/project/prjprdvehinfo")
public class PrjPrdVehInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(PrjPrdVehInfoController.class);

	/**
	 * PrjPrdVehInfo 服务层BEAN
	 */
	@Autowired
	private IPrjPrdVehInfoService prjPrdVehInfoService;
	@Autowired
	private ICstBscInfoService cstBscInfoService;
	/**
	 * PrjBscInfo 服务层BEAN
	 */
	@Autowired
	private IPrjBscInfoService prjBscInfoService;
	/**
	 * 文件 服务层BEAN
	 */
	@Autowired
	private ISysUlFilesRecService sysUlFilesRecService;

	/**
	 * PrjBscInfo 服务层BEAN
	 */
	@Autowired
	private IPrjPrdDtlService prjPrdDtlService;
	@Autowired
	private IPrjPrdExtApiService prjPrdExtApiService;

	/**
	 * PrjBscInfo 服务层BEAN
	 */
	@Autowired
	private IPrjPrdDtlTkService prjPrdDtlTkService;

	@Autowired
	private IPrjPrdDtlCarService prjPrdDtlCarService;

	@Autowired
	private IPrjPrdBscInfoService prjPrdBscInfoService;
	@Autowired
	private ISysUlDatCfgService sysUlDatCfgService;

	@Autowired
	private IPrjPrdDtlGpsService prjPrdDtlGpsService;

	@Autowired
	private ICheckInvoiceApiService checkInvoiceApiService;

	@Autowired
	private IPrjPrdLicInfoService prjPrdLicInfoService;

	@Autowired
	IDeviceInfoApiService deviceInfoApiService;

	@Autowired
	IProjectApiService projectApiService;

	@Autowired
	private IPrjPrdChangeApplyService prjPrdChangeApplyService;

	/**
	 * 系统用户
	 */
	@Autowired
	private ISysUsrApiService sysUsrApiService;

	@Autowired
	private IPrjPrdDtlGpsApiService prjPrdDtlGpsApiService;

	@Autowired
	private PrjPrdDtlController prjPrdDtlController;

	@Autowired
	private IPrjPrdChangeApplyApiService prjPrdChangeApplyApiService;
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = {  RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("project/prjprdvehinfo/prjPrdVehInfolistPage");
		List<KeyValueVO> buOrgCdList = this.cstBscInfoService.searchBusinessOrgList();//事业部
		//项目类型
		List<KeyValueVO> projectTypeList = this.prjBscInfoService.getPrjTypCdALLKV();
		//业务类型
		List<KeyValueVO> bizTypeList = this.prjBscInfoService.getBizTypeList();
		List<KeyValueVO> isYesList  = this.cstBscInfoService.searchYNList();
		// GPS审核状态
		List<KeyValueVO> gpsAudStsList = this.prjBscInfoService.getGPSAudStsList();
        //合格证审核状态
        List<KeyValueVO> certNoAudStsCd = prjBscInfoService.getAudStsList();

        view.addObject("certNoAudStsCd", certNoAudStsCd);
		view.addObject("buOrgCdList", buOrgCdList);
		view.addObject("projectTypeList", projectTypeList);
		view.addObject("bizTypeList", bizTypeList);
		view.addObject("isYesList", isYesList);
		view.addObject("gpsAudStsList", gpsAudStsList);
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}


	/**
	 * 到详细页面
	 */
	@RequestMapping(value = "/toDetailPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toDetailPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		String detailFlag = request.getParameter("detailFlag");
		String dtlId = request.getParameter("dtlId");//产品明细
		//换车-dtl表中获取不到prjId、paySchId、paySchNo
		String prjId = request.getParameter("prjId");
		String paySchId = request.getParameter("paySchId");
		String paySchNo = request.getParameter("paySchNo");
		ModelAndView view = new ModelAndView("project/prjprdvehinfo/prjPrdVehInfoDetailPage");
		PrjPrdVehInfoVO vehInfo = null;
		if(StringUtils.isNotBlank(id)){
			vehInfo = 	this.prjPrdVehInfoService.selectById(Long.valueOf(id));
		}else{
			vehInfo = this.prjPrdVehInfoService.selectByDtlId(Long.valueOf(dtlId));
		}

		if(null != vehInfo){//关键字转换 FUJINGRUN
			String cstNm = vehInfo.getCstNm();
			if(StringUtils.isNotEmpty(cstNm)){
				for (String key : ResponseFilter.keyList) {
					if (cstNm.contains(key)) {
						cstNm = cstNm.replace(key, ResponseFilter.convertKeyMap.get(key));
					}
				}
				vehInfo.setCstNm(cstNm);
			}
		}
		//支付表号、支付表ID赋值
		if (vehInfo != null) {
			if (vehInfo.getPaySchId() == null && StringUtils.isNotEmpty(paySchId)) {
				vehInfo.setPaySchId(Long.valueOf(paySchId));
			}
			if (StringUtils.isEmpty(vehInfo.getPaySchNo()) && StringUtils.isNotEmpty(paySchNo)) {
				vehInfo.setPaySchNo(paySchNo);
			}
			if (StringUtils.isEmpty(vehInfo.getLsCntNo()) && StringUtils.isNotEmpty(prjId)) {
				PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(Long.valueOf(prjId));
				if (prjBscInfoVO != null) {
					vehInfo.setLsCntNo(prjBscInfoVO.getLsCntNo());
					if (vehInfo.getPrjId() == null) {
						vehInfo.setPrjId(prjBscInfoVO.getId());
					}
					if (StringUtils.isEmpty(vehInfo.getPrjTypCd())) {
						vehInfo.setPrjTypCd(prjBscInfoVO.getPrjTypCd());
					}
					if (StringUtils.isEmpty(vehInfo.getBizTypCd())) {
						vehInfo.setBizTypCd(prjBscInfoVO.getBizTypCd());
					}
					if (StringUtils.isEmpty(vehInfo.getCstNm())) {
						vehInfo.setCstNm(prjBscInfoVO.getCstNm());
					}
				}
			}
		}
		//更多的gps卡号
		PrjPrdDtlGpsQueryCondition condition = new PrjPrdDtlGpsQueryCondition();
		condition.setPrjDtlId(Long.valueOf(dtlId));;
		List<PrjPrdDtlGpsVO> voList = this.prjPrdDtlGpsService.searchList(condition);
		view.addObject("moreGpsList", voList);
		view.addObject("id", id==null?"":id);
		view.addObject("vehInfo", vehInfo);
		view.addObject("detailFlag", detailFlag);
		view.addObject("dtlId", dtlId);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	/**
	 * 到添加页面
	 * @param isGpsNode 是否风控审批GPS节点  1:是 0：否
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response,@RequestParam(required = false,defaultValue = "0") String isGpsNode) {
		String id = request.getParameter("id");
		String detailFlag = request.getParameter("detailFlag");
		String dtlId = request.getParameter("dtlId");//产品明细
		String handleType = request.getParameter("handleType");// 操作类型， 1-跳转到变更GPS页面
		//0 表示不可以编辑 1表示可以编辑
		String isEdit = request.getParameter("isEdit");
		//GPS变更申请id
		String applyId = request.getParameter("applyId");
		//换车-dtl表中获取不到prjId、paySchId、paySchNo
		String prjId = request.getParameter("prjId");
		String paySchId = request.getParameter("paySchId");
		String paySchNo = request.getParameter("paySchNo");
		String prjPrdChangeFlag = request.getParameter("prjPrdChangeFlag");
		if(StringUtils.isNotEmpty(applyId)){
			try {
				BaseLogUtils.info(logger, "selectById", "查询GPS申请表请求参数是"+JSON.toJSONString(applyId));
				PrjPrdGpsApplyDTO selectById = prjPrdGpsApplyApiService.selectById(Long.parseLong(applyId));
				BaseLogUtils.info(logger, "selectById", "查询GPS申请表返回结果是"+JSON.toJSONString(selectById));
				dtlId = selectById.getPrjPrdDtlId().toString();
				//获取实际车辆id
				PrjPrdDtlVO selectById2 = prjPrdDtlService.selectById(Long.parseLong(dtlId));
				id = selectById2.getActPrdId().toString();
				detailFlag = "false";
				handleType = "1";
				isGpsNode = "1";
			} catch (Exception e) {
				BaseLogUtils.info(logger, "selectById", "查询GPS申请表错误信息是"+e.getMessage());
			}
		}
        ModelAndView view = null;
		if (StringUtils.isNotEmpty(handleType) && "1".equals(handleType)){
		    view = new ModelAndView("project/prjprdvehinfo/prjPrdVehInfoAddPage_changGPS");
		} else {
		    view = new ModelAndView("project/prjprdvehinfo/prjPrdVehInfoAddPage");
        }

		PrjPrdVehInfoVO vehInfo = null;
		if(StringUtils.isNotEmpty(id)){
			vehInfo = 	this.prjPrdVehInfoService.selectById(Long.valueOf(id));
		} else {
			vehInfo = this.prjPrdVehInfoService.selectByDtlId(Long.valueOf(dtlId));
		}
		String orgCd = PrjBscInfoConstant.CODE_PRJ_FILE_DEF_ORG;
		//GPS审核状态
		PrjPrdDtlGpsQueryCondition condition = new PrjPrdDtlGpsQueryCondition();
		condition.setPrjDtlId(Long.valueOf(dtlId));
		condition.setSerialNo(1);
		List<PrjPrdDtlGpsVO> voList = this.prjPrdDtlGpsService.searchList(condition);
		//查询项目的事业部
		PrjPrdDtlVO dtl = this.prjPrdDtlService.selectById(Long.valueOf(dtlId));
		if(null != dtl){
			String prdStsCd = dtl.getPrdStsCd();//查询资产状态
			view.addObject("prdStsCd",prdStsCd);
			Long projectId = dtl.getPrjId();
			if (projectId == null && StringUtils.isNotEmpty(prjId)) {
				projectId = Long.valueOf(prjId);
			}
			PrjBscInfoVO prjBsc = 	this.prjBscInfoService.selectById(projectId);
			if(null!=prjBsc){
				orgCd = prjBsc.getBuOrgCd();
				String prjTypCd = prjBsc.getPrjTypCd();//项目类型查询
				view.addObject("prjTypCd",prjTypCd);
				if (vehInfo.getPrjId() == null) {
					vehInfo.setPrjId(prjBsc.getId());
				}
				if (StringUtils.isEmpty(vehInfo.getPrjTypCd())) {
					vehInfo.setPrjTypCd(prjBsc.getPrjTypCd());
				}
				if (StringUtils.isEmpty(vehInfo.getBizTypCd())) {
					vehInfo.setBizTypCd(prjBsc.getBizTypCd());
				}
				if (StringUtils.isEmpty(vehInfo.getLsCntNo())) {
					vehInfo.setLsCntNo(prjBsc.getLsCntNo());
				}
				if (StringUtils.isEmpty(vehInfo.getCstNm())) {
					vehInfo.setCstNm(prjBsc.getCstNm());
				}
			}
            // 产品类型
            PrjPrdBscInfoVO prjPrdBscInfoVO = this.prjPrdBscInfoService.selectById(dtl.getPrjPrdId());
            view.addObject("prdTypCd",prjPrdBscInfoVO.getPrdTypCd());
		}
		//支付表号、支付表ID赋值
		if (vehInfo != null) {
			if (vehInfo.getPaySchId() == null && StringUtils.isNotEmpty(paySchId)) {
				vehInfo.setPaySchId(Long.valueOf(paySchId));
			}
			if (StringUtils.isEmpty(vehInfo.getPaySchNo()) && StringUtils.isNotEmpty(paySchNo)) {
				vehInfo.setPaySchNo(paySchNo);
			}
		}
		//查找上传的合格证照片信息
		SysUlFilesRecQueryCondition fileQc = new SysUlFilesRecQueryCondition();
		fileQc.setCfgCd(PrjPrdBscInfoConstant.PRJ_PRD_FILE_CFG_CODE);
		fileQc.setCfgDtlCd(PrjPrdBscInfoConstant.PRJ_PRD_FILE_VEH_PHOTO_CODE);
		fileQc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		fileQc.setPkId(dtlId);
		fileQc.setTabNm(PrjPrdBscInfoConstant.PRJ_PRD_FILE_VEH_PHOTO_TABLE_NM);
		List<SysUlFilesRecVO> list = this.sysUlFilesRecService.searchList(fileQc);
		String imgPath = "";
        if(CollectionUtils.isNotEmpty(list)){
            imgPath = list.get(0).getFilePath();
        }
		String serverPath = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_SERVER_PATH);//服务地址
		String customerPah = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_COSTOMER_PATH);
		String headPic = PropertiesCacheUtils.getProperty(fl.constant.facade.framework.constant.UploadConstant.DEFAULT_NO_PIC);
		//查询文件主code
		SysUlDatCfgQueryCondition qc = new SysUlDatCfgQueryCondition();
		List<String> codeList = new ArrayList<String>();
		codeList.add(PrjPrdBscInfoConstant.PRJ_PRD_FILE_CFG_CODE);
		qc.setCfgCdList(codeList);
		qc.setOrgCd(orgCd);
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		String  sysCdStr = "";
		String orgCdStr = "";
		List<SysUlDatCfgVO> cfgList = sysUlDatCfgService.searchList(qc);
		List<SysUlDatCfgDtlVO> dtlList = cfgList.get(0).getSysUlDatCfgDtlVOList();
		for (SysUlDatCfgDtlVO sysUlDatCfgDtlVO : dtlList) {
			if(PrjPrdBscInfoConstant.PRJ_PRD_FILE_VEH_PHOTO_CODE.equals(sysUlDatCfgDtlVO.getCfgDtlCd())){
				sysCdStr = sysUlDatCfgDtlVO.getSysCd();
				orgCdStr = sysUlDatCfgDtlVO.getOrgCd();
				break;
			}
		}

		view.addObject("id", id==null?"":id);
		view.addObject("vehInfo", vehInfo);
		view.addObject("detailFlag", detailFlag);
		view.addObject("dtlId", dtlId);
		view.addObject("filePath", imgPath);
		view.addObject("sysCd", sysCdStr);
		view.addObject("orgCd", orgCdStr);
		view.addObject("buOrgCd", orgCd);
		view.addObject("cfgCd", PrjPrdBscInfoConstant.PRJ_PRD_FILE_CFG_CODE);
		view.addObject("cfgDtlCd", PrjPrdBscInfoConstant.PRJ_PRD_FILE_VEH_PHOTO_CODE);
		view.addObject("cfgDtlQtCd", PrjPrdBscInfoConstant.PRJ_PRD_FILE_VEH_PHOTO_QT_CODE);
		view.addObject("defImg", serverPath+customerPah+headPic);
		view.addObject("list", list);
		view.addObject("isGpsNode", isGpsNode);
		view.addObject("handleType", handleType);
		view.addObject("isEdit", isEdit);
		if (null != voList && voList.size() > 0){
			view.addObject("gpsAudStsCd", voList.get(0).getAudStsCd());// GPS审核状态
		}
		// 车抵贷业务（线下）、二手车交易贷 信审审核节点、信审审核抵押节点、信审审核上牌抵押节点 隐藏挂靠公司更改/移除按钮
		view.addObject("noLinkAction", request.getParameter("noLinkAction"));
		view.addObject("noLinkButton", request.getParameter("noLinkButton"));
		//换车标志
		view.addObject("prjPrdChangeFlag",prjPrdChangeFlag);
		view.addObject("prjId",prjId);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改或新增页面dtlId=" + dtlId + "id=" + id == null ? "" : id
                + "view=" + JSON.toJSONString(view), CurrentThreadContext.getCurrentUserName());
		return view;
	}
	/**
	 * 到扫描页面
	 */
	@RequestMapping(value = "/toScanPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toScanPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("project/prjprdvehinfo/toScanPage");
		BaseLogUtils.info(logger, "toScanPage", "跳转到到扫描页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}


	/**
	 * 到合格证产品型号和产品明细型号对比页面
	 */
	@RequestMapping(value = "/toCompPrdInfoListPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toCompPrdInfoListPage(HttpServletRequest request, HttpServletResponse response) {
		String dtlId = request.getParameter("dtlId");//产品明细
		String isAuditNode = request.getParameter("isAuditNode");//信审节点
		String taskDefKey = request.getParameter("taskDefKey");//节点key
		String buOrg = request.getParameter("buOrg");//节点key
		String prdTypCd = "";
		PrjPrdDtlVO dtlVO = this.prjPrdDtlService.selectById(Long.valueOf(dtlId));
		int hasTkFlag=0;
		int hasCarFlag=0;
		String prjTypCd = "";
		ModelAndView view = new ModelAndView("project/prjprddtl/prjPrdDtlPrdInfoListPage");
		if(null!=dtlVO){
			PrjPrdBscInfoVO prjPrd = this.prjPrdBscInfoService.selectById(dtlVO.getPrjPrdId());
			if(null!=prjPrd){
				prdTypCd = prjPrd.getPrdTypCd();
			}
		}
		String buOrgCd = "";
		if(null != dtlVO){
			PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(dtlVO.getPrjId());
			if(null != prjBscInfoVO){
				view.addObject("buOrgCd", prjBscInfoVO.getBuOrgCd());
				buOrgCd = prjBscInfoVO.getBuOrgCd();
				prjTypCd = prjBscInfoVO.getPrjTypCd();
			}
		}

		if(!prdTypCd.equals(CarStyleConstant.PRD_TYPE_11)
				||prdTypCd.equals(CarStyleConstant.PRD_TYPE_7)
				||prdTypCd.equals(CarStyleConstant.PRD_TYPE_52)){
			view = new ModelAndView("project/prjprddtl/prjPrdDtlPrdInfoListPage");

			PrjPrdExtDTO prjPrdExtDTO = this.prjPrdExtApiService.selectById(Long.parseLong(dtlId));
			if(prjPrdExtDTO!=null){
				hasCarFlag=BaseConstant.IS_YESNO_YES;
				hasTkFlag=BaseConstant.IS_YESNO_YES;
			}
//			PrjPrdDtlTkVO tk = this.prjPrdDtlTkService.selectById(Long.valueOf(dtlId));
//			if(null==tk){
//				PrjPrdDtlCarVO car = this.prjPrdDtlCarService.selectById(Long.valueOf(dtlId));
//				if(null==car){
//					hasTkFlag = BaseConstant.IS_YESNO_NO;
//				}else{
//					hasCarFlag = BaseConstant.IS_YESNO_YES;
//					hasTkFlag = BaseConstant.IS_YESNO_YES;
//				}
//			}else{
//				hasTkFlag = BaseConstant.IS_YESNO_YES;
//			}
		}else{
			view = new ModelAndView("project/prjprddtl/prjPrdDtlCarPrdInfoListPage");
		}
		if((StringUtils.isNotBlank(buOrgCd) && "00000008".equals(buOrgCd))||(prdTypCd.equals("11"))){
			view = new ModelAndView("project/prjprddtl/prjPrdDtlPrdInfoListPageForSpecialCar");
		}
		view.addObject("dtlId", dtlId);
		view.addObject("isAuditNode", isAuditNode);
		view.addObject("hasTkFlag", hasTkFlag);
		view.addObject("hasCarFlag", hasCarFlag);
		view.addObject("taskDefKey", taskDefKey);
		view.addObject("buOrgCd", buOrgCd);
		view.addObject("prjTypCd", prjTypCd);

		BaseLogUtils.info(logger, "toCompPrdInfoListPage", "跳转到到合格证产品型号和产品明细型号对比页面.[dtlId="+dtlId+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}



	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		ModelAndView view = new ModelAndView("project/prjprdvehInfo/modify");
		view.addObject("id", id);
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String lsCntNo = request.getParameter("lsCntNo");
		String paySchNo = request.getParameter("paySchNo");
		String cstNm = request.getParameter("cstNm");
		String buOrgCd = request.getParameter("buOrgCd");
		String certNo = request.getParameter("certNo");
		String prjTypCd = request.getParameter("prjTypCd");
		String bizTypCd = request.getParameter("bizTypCd");
		String isUploadFile = request.getParameter("isUploadFile");//资料是否上传
		String isHaveVeh = request.getParameter("isHaveVeh");//是否录入合格证信息
		String gpsAudStsCd = request.getParameter("gpsAudStsCd");//GPS审核状态
        String certNoAudStsCd = request.getParameter("certNoAudStsCd");//合格证审核状态

		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		PrjPrdVehInfoQueryCondition qc = new PrjPrdVehInfoQueryCondition();
		if (StringUtils.isNotEmpty(lsCntNo)) {
			qc.setLsCntNo(lsCntNo);
		}
		if(StringUtils.isNotBlank(isUploadFile)){
			qc.setIsUploadFile(Integer.valueOf(isUploadFile));
		}
		if(StringUtils.isNotBlank(isHaveVeh)){
			qc.setIsHaveVeh(Integer.valueOf(isHaveVeh));
		}
		if (StringUtils.isNotEmpty(paySchNo)) {
			qc.setPaySchNo(paySchNo);
		}
		if (StringUtils.isNotEmpty(cstNm)) {
			qc.setCstNm(cstNm);
		}
		if (StringUtils.isNotEmpty(buOrgCd)) {
			qc.setBuOrgCd(buOrgCd);
		}
		if (StringUtils.isNotEmpty(certNo)) {
			qc.setCertNo(certNo);
		}
		if (StringUtils.isNotEmpty(prjTypCd)) {
			qc.setPrjTypCd(prjTypCd);
		}
		if (StringUtils.isNotEmpty(bizTypCd)) {
			qc.setBizTypCd(bizTypCd);
		}
		if (StringUtils.isNotEmpty(gpsAudStsCd)){// GPS审核状态
			qc.setGpsAudStsCd(Integer.valueOf(gpsAudStsCd));
		}
        if (StringUtils.isNotEmpty(certNoAudStsCd)){// 合格证审核状态
            qc.setAudStsCd(certNoAudStsCd);
        }

		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		qc.setCfgCd(PrjBscInfoConstant.CODE_PRJ_PRD_FILE_CD);
		qc.setCfgDtlCd(PrjPrdBscInfoConstant.PRJ_PRD_FILE_VEH_PHOTO_CODE);
		qc.setUsrId(CurrentThreadContext.getCurrentUserId());
		page.setCondition(qc);

		Pager pager = this.prjPrdVehInfoService.searchListPage(page);
		List<PrjPrdVehInfoVO> list = (List<PrjPrdVehInfoVO>) pager.getResultList();
		ListPageVO<PrjPrdVehInfoVO> listPage = new ListPageVO<PrjPrdVehInfoVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}


	/**
	 * 产品明细、卡车乘用车列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getPrjPrdDtlPrdInfoInitList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getPrjPrdDtlPrdInfoInitList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String dtlId = request.getParameter("dtlId");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		PrjPrdVehInfoQueryCondition qc = new PrjPrdVehInfoQueryCondition();
		if(StringUtils.isNotBlank(dtlId)){
			qc.setDtlId(Long.valueOf(dtlId));
		}
		page.setCondition(qc);

		Pager pager = this.prjPrdVehInfoService.getPrjPrdDtlPrdInfoInitListPage(page);
		List<PrjPrdVehInfoVO> list = (List<PrjPrdVehInfoVO>) pager.getResultList();
		ListPageVO<PrjPrdVehInfoVO> listPage = new ListPageVO<PrjPrdVehInfoVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(listPage), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}



	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(ids)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		List<Long> idList = new ArrayList<Long>();
		JSONArray idsArray = JSONArray.fromObject(ids);
		for (Object object : idsArray) {
			idList.add(Long.valueOf(object.toString()));
		}
		try {
			this.prjPrdVehInfoService.removeByIds(idList);
			BaseLogUtils.info(logger, "removeById", "删除数据.[ids="+ids+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[ids="+ids+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+ids+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}
	/**
	 * 得到一条记录
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/checkCertNo.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object checkCertNo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String certNo = request.getParameter("certNo");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		try {
			PrjPrdVehInfoQueryCondition qc = new PrjPrdVehInfoQueryCondition();
			qc.setCertNo(certNo);
			List<PrjPrdVehInfoVO> list = this.prjPrdVehInfoService.searchList(qc);
			result.setData(list);
			BaseLogUtils.info(logger, "checkCertNo", "获取数据.[certNo="+certNo+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "checkCertNo", "获取失败.[certNo="+certNo+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "checkCertNo", "获取失败.[certNo="+certNo+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 得到一条记录
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/checkPrjPrdVehVinExist.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object checkPrjPrdVehVinExist(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String vin = request.getParameter("vin");

		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		boolean flag  = false;
		try {
			PrjPrdVehInfoQueryCondition qc = new PrjPrdVehInfoQueryCondition();
			qc.setVin(vin);
			flag = this.prjPrdVehInfoService.checkPrjPrdVehVinExist(qc);
			if(flag){
				result.setSuccess(BaseConstant.IS_YESNO_YES);
			}else{
				result.setSuccess(BaseConstant.IS_YESNO_NO);
			}
			BaseLogUtils.info(logger, "checkPrjPrdVehVinExist", "获取数据.[flag="+flag+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "checkPrjPrdVehVinExist", "获取失败.[flag="+flag+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "checkPrjPrdVehVinExist", "获取失败.[flag="+flag+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}


	/**
	 * 得到一条记录
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getPrjPrdVehInfo.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object getPrjPrdVehInfo(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String baseStr = request.getParameter("baseStr");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(baseStr)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("获取扫描信息失败,请重新扫描！");
			BaseLogUtils.error(logger, "getPrjPrdVehInfo", "获取扫描信息失败！", CurrentThreadContext.getCurrentUserName());
			return result;
		}

		try {
			PrjPrdVehInfoVO vo = this.prjPrdVehInfoService.getPrjPrdVehInfoByScanStr(baseStr);
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "解析数据失败!", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "解析数据失败!", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id=]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id=]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 得到一条记录
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}

		try {
			PrjPrdVehInfoVO vo = this.prjPrdVehInfoService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 校验vin与GPS
	 * @param dtlId 产品明细id
	 * @param entity PrjPrdVehInfoVO 车辆信息对象
	 * @param gpsNums GPS卡号字符串，如："卡号1,卡号2,"
	 */
	private void modifyVinAndGPS(String dtlId, PrjPrdVehInfoVO entity, String gpsNums, String prjPrdChangeFlag){
		if(StringUtils.isNotBlank(dtlId)){
			//查询vin是否跟手机端的一致
			PrjPrdDtlQueryCondition qc = new PrjPrdDtlQueryCondition();
			List<Long> idList = new ArrayList<Long>();
			idList.add(Long.valueOf(dtlId));
			qc.setIdList(idList);
			List<PrjPrdDtlVO>  prjPrdList = this.prjPrdDtlService.selectList(qc);
			if(CollectionUtils.isNotEmpty(prjPrdList)){
				PrjPrdDtlVO dtlVO = prjPrdList.get(0);
                // 挂车不校验
                if(null!=dtlVO ){
                	//换车修改VIN时不校验该项
					if(StringUtils.isNotBlank(dtlVO.getVin()) && !"true".equals(prjPrdChangeFlag)){
						if(!dtlVO.getVin().equals(entity.getVin())){
							throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"合格证车架号和手机端扫描的vin不一致！");
						}
					}
					if(!"1".equals(entity.getVinValidRes())){
						throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604,"错误，请修改ViN信息");
					}
				}
			}

			// 验证GPS卡号
			String[] gpsNumsArray = gpsNums.split(",");
			if (!cheakIsRepeat(gpsNumsArray)) {
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"填写的GPS重复，请调整!");
			}

			if (gpsNumsArray.length > 0){
				for (int i = 0; i<gpsNumsArray.length; i++){
					if(StringUtils.isNotBlank(gpsNumsArray[i]) && !"0".equals(gpsNumsArray[i])){
						Integer checkResult = prjPrdDtlGpsService.checkGPSExist(gpsNumsArray[i], Long.valueOf(dtlId));
						if (checkResult != 1){// 0表示占用 1表示未占用 2 数据错误
							throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"当前资产GPS信息已在其它资产上绑定使用，请调整!");
						}
					}
				}

				// 校验GPS卡号是否属于当前用户已领用,排除为空或0 的数据
				PrjPrdDtlVO prjPrdDtlVO = this.prjPrdDtlService.selectById(Long.valueOf(dtlId));
				Long prjId = prjPrdDtlVO.getPrjId();
				if (prjId == null) {
					PrjPrdChangeApplyQC prjPrdChangeApplyQC = new PrjPrdChangeApplyQC();
					prjPrdChangeApplyQC.setNewPrjPrdDtlId(Long.valueOf(dtlId));
					List<PrjPrdChangeApplyVO> prjPrdChangeApplyVOS = this.prjPrdChangeApplyService.selectList(prjPrdChangeApplyQC);
					if (CollectionUtils.isNotEmpty(prjPrdChangeApplyVOS)) {
						prjId = prjPrdChangeApplyVOS.get(0).getPrjId();
					}
				}
				PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(prjId);
				String cstMgrOrgCd = prjBscInfoVO.getCstMgrOrgCd();
				if(StringUtils.isBlank(cstMgrOrgCd)){
					throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"未查询到客户经理组织机构代码");
				}
				// 取消GPS卡号与客户经理名下已领用数据一致校验性
				// 之前的:专车客车事业部特殊处理，不校验 现在是:全体事业部
				/*if(!cstMgrOrgCd.startsWith("000000080002")){
					List<String> gpsDeviceList = this.prjPrdDtlGpsService.getGpsDevice(prjBscInfoVO.getCstMgrId(),"2");
					// 历史数据处理：
					PrjPrdDtlGpsQueryCondition prjPrdDtlGpsQueryCondition = new PrjPrdDtlGpsQueryCondition();
					prjPrdDtlGpsQueryCondition.setIsDel(0);
					prjPrdDtlGpsQueryCondition.setPrjDtlId(Long.valueOf(dtlId));
					List<PrjPrdDtlGpsVO> prjPrdDtlGpsVOS = prjPrdDtlGpsService.searchList(prjPrdDtlGpsQueryCondition);
					for (int i = 0; i<gpsNumsArray.length; i++){
						if(StringUtils.isNotBlank(gpsNumsArray[i]) && !"0".equals(gpsNumsArray[i])){
							// 历史数据，已存在GPS已领用状态，大数据系统不返回，保存时不校验
							if(CollectionUtils.isNotEmpty(prjPrdDtlGpsVOS)){
								boolean containsFlag = false;
								for(PrjPrdDtlGpsVO prjPrdDtlGpsVO : prjPrdDtlGpsVOS){
									if(Objects.equals(prjPrdDtlGpsVO.getGpsCardNo(),gpsNumsArray[i])){
										containsFlag = true;
										break;
									}
								}
								if(containsFlag){
									break;
								}
							}
							if(CollectionUtils.isEmpty(gpsDeviceList)){
								throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"项目客户经理账号下未查询到设备，请核实");
							}
							boolean flag = false;
							for(String gps : gpsDeviceList){
								if(Objects.equals(gpsNumsArray[i],gps)){
									flag = true;
									break;
								}
							}
							if(!flag){
								BaseLogUtils.newLogger("GPS卡号录入有误，请核实,gpsCarNo={}",gpsNumsArray[i]).info();
								throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"GPS卡号录入有误，请核实");
							}
						}
					}
				}*/
			}

		}
	}

	/*
	 * 判断数组中是否有重复的值
	 */
	public static boolean cheakIsRepeat(String[] array) {
		BaseLogUtils.info(logger, "cheakIsRepeat: ", "cheakIsRepeat: " +JSON.toJSONString(array), CurrentThreadContext.getCurrentUserName());
		HashSet<String> hashSet = new HashSet<String>();
		for (int i = 0; i < array.length; i++) {
			if (array[i].equals("0")){
				hashSet.add(i+"0");
			} else {
				hashSet.add(array[i]);
			}

		}
		BaseLogUtils.info(logger, "cheakIsRepeat: ", "cheakIsRepeat1: " +JSON.toJSONString(hashSet), CurrentThreadContext.getCurrentUserName());
		if (hashSet.size() == array.length) {
			return true;
		} else {
			return false;
		}
	}


	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");// id
		String dtlId = request.getParameter("dtlId");//产品明细
		String gpsNums  = request.getParameter("gpsNums");// GPS卡号,示例数据："卡号1,卡号2,"
		String gpsAudStsCd  = request.getParameter("gpsAudStsCd");// GPS审核状态
		String audStsCd  = request.getParameter("audStsCd");// 合格证审核状态
		String isGpsNode = request.getParameter("isGpsNode");// 是否风控审批GPS节点，0-否，1-是
		String prjPrdChangeFlag = request.getParameter("prjPrdChangeFlag");//换车标志
		String prjId = request.getParameter("prjId");
		BaseLogUtils.newLogger("GPS卡号信息（gpsNums）:" + JSONObject.toJSONString(gpsNums) + CurrentThreadContext.getCurrentUserName()).info();
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		PrjPrdVehInfoVO entity = null;
		Long vehId = null;
        int cpSts = BaseConstant.IS_YESNO_NO;
		try {
			entity = this.getRequestParams(request);
			this.modifyVinAndGPS(dtlId, entity, gpsNums, prjPrdChangeFlag);
            //如果该合格证对应的项目为城配业务  判断该项目流程的流程状态  若流程initList.do已发起 新增合格证信息的时候  设置合格证的状态、GPS状态为审核中
            cpSts = this.getCpSts(Long.valueOf(dtlId));
			if(StringUtils.isNotBlank(id)){
				entity.setId(Long.valueOf(id));
				vehId = Long.valueOf(id);
				prjPrdVehInfoService.modify(entity);
				result.setSuccess(BaseConstant.IS_YESNO_YES);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_SUCC);
			}else{
				//添加合格证信息
				entity.setIsDel(BaseConstant.IS_YESNO_NO);
				if(cpSts == BaseConstant.IS_YESNO_YES){
                    entity.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
                }else{
                    entity.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_NON);
                }
				entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				entity.setCrtTm(new  Date());
				vehId = this.prjPrdVehInfoService.add(entity);
				result.setSuccess(BaseConstant.IS_YESNO_YES);
				result.setInfo(SysLogConstant.LOG_CMM_ADD_SUCC);
			}
			PrjPrdDtlVO dtl = this.prjPrdDtlService.selectById(Long.valueOf(dtlId));
			dtl.setEngNo(entity.getEngNo());
			dtl.setVin(entity.getVin().trim());
			dtl.setVinValidRes(entity.getVinValidRes());
			this.prjPrdDtlService.modify(dtl);

			PrjBscInfoVO prjBscInfoVO = null;
			if (StringUtils.isNotEmpty(prjId)) {
				prjBscInfoVO = this.prjBscInfoService.selectById(Long.valueOf(prjId));
			} else {
			   prjBscInfoVO = this.prjBscInfoService.selectById(dtl.getPrjId());
			}

			saveGPS(gpsNums, dtlId,prjBscInfoVO);
			BaseLogUtils.newLogger("实时发送设备信息开始入参dtlId=" + dtlId).info();
			boolean b = deviceInfoApiService.sendDeviceInfo(Long.valueOf(dtlId));
			BaseLogUtils.newLogger("实时发送设备信息返回结果dtlId=" + dtlId + "b=" + b).info();
			result.setData(vehId);
			BaseLogUtils.newLogger("保存合格证或GPS数据dtlId=" + dtlId + JSONObject.toJSONString(entity) + CurrentThreadContext.getCurrentUserName()).info();
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.newLogger("保存合格证或GPS数据异常dtlId=" + dtlId + JSONObject.toJSONString(entity) + ex.getMessage() + CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.API_CODE_0102);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.newLogger("保存合格证或GPS数据异常dtlId=" + dtlId + JSONObject.toJSONString(entity) + ex.getMessage() + CurrentThreadContext.getCurrentUserName()).setThrowable(ex).error(LogExceptionEnum.API_CODE_0102);
		}
		return result;
	}

	/**
	 * @description 校验gps信息
	 * @param request
	 * @param response
	 * @return
	 * @throws BaseException
	 */
	@RequestMapping(value = "/validateGps.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object validateGps(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO resultVO = new DataResultVO(BaseConstant.IS_YESNO_YES);
		// gps卡1
		String gps1 = request.getParameter("gps1");
		// gps卡2
		String gps2 = request.getParameter("gps2");
		// gps卡3
		String gps3 = request.getParameter("gps3");
		//项目产品明细id
		String dtlId = request.getParameter("dtlId");
		// 项目id
		String prjId = request.getParameter("prjId");

		BaseLogUtils.newLogger("产品明细id:{},合格证管理的点击保存校验gps信息,gps卡号1:{},gps卡号2:{},gps卡号3:{}",dtlId,gps1,gps2,gps3).info();

		if (StringUtils.isEmpty(dtlId)) {
			resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
			resultVO.setInfo("未找到产品明细id");
			return resultVO;
		}

		PrjPrdDtlVO prjPrdDtlVO = this.prjPrdDtlService.selectById(Long.valueOf(dtlId));
		BaseLogUtils.newLogger("产品明细id:{},查询的产品明细信息:{}",dtlId,JSON.toJSONString(prjPrdDtlVO, SerializerFeature.WriteMapNullValue)).info();

		if (null == prjPrdDtlVO) {
			resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
			resultVO.setInfo("未找到项目产品明细信息!");
			BaseLogUtils.newLogger("产品明细id:{},合格证管理的点击保存,未找到项目产品明细信息:{}",dtlId,JSON.toJSONString(resultVO)).info();
			return resultVO;
		}

		// 校验卡号的重复性
		List<String> list1 = new ArrayList<>();
		String gps11 = StringUtils.isNotBlank(gps1) ? gps1 : "0";
		String gps22 = StringUtils.isNotBlank(gps2) ? gps2 : "0";
		String gps33 = StringUtils.isNotBlank(gps3) ? gps3 : "0";

		list1.add(gps11);
		list1.add(gps22);
		list1.add(gps33);
		BaseLogUtils.newLogger("产品明细id:{},合格证管理的点击保存,校验gps卡号重复性:{}",dtlId,JSON.toJSONString(list1)).info();

		List checkList = new ArrayList();
		for(String gpsCardNo:list1){
			if(StringUtils.isNotBlank(gpsCardNo) && !gpsCardNo.equals("0")){
				if(checkList.contains(gpsCardNo)){
					resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
					resultVO.setInfo("GPS卡号有重复,请核查!");
					return resultVO;
				}
				checkList.add(gpsCardNo);
			}
		}



		// 校验gps卡号纯数字、数字长度
		List<String> errorMsgList = new ArrayList<>();
		prjPrdDtlController.validateGpsCardNo(gps1,errorMsgList);
		prjPrdDtlController.validateGpsCardNo(gps2,errorMsgList);
		prjPrdDtlController.validateGpsCardNo(gps3,errorMsgList);

		BaseLogUtils.newLogger("产品明细id:{},合格证管理的点击保存校验gps错误信息:{}",dtlId).info();
		if (CollectionUtils.isNotEmpty(errorMsgList)) {
			resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
			resultVO.setInfo(errorMsgList.toString());
			BaseLogUtils.newLogger("产品明细id:{},合格证管理的点击保存校验gps错误信息:{}",dtlId,JSON.toJSONString(resultVO)).info();
			return resultVO;
		}


		Long projectId = null;
		if (StringUtils.isBlank(prjId)) {
			projectId = prjPrdDtlVO.getPrjId();
		} else {
			projectId = Long.valueOf(prjId);
		}

		BaseLogUtils.newLogger("产品明细id:{},项目id:{}",dtlId,projectId).info();

		PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(projectId);
		BaseLogUtils.newLogger("产品明细id:{},项目id:{},项目基本信息:{}",dtlId,projectId,JSON.toJSONString(prjBscInfoVO)).info();

		if (null == prjBscInfoVO) {
			resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
			resultVO.setInfo("未找到该项目!");
			BaseLogUtils.newLogger("产品明细id:{},合格证管理的点击保存,未找到该项目,{}",dtlId,JSON.toJSONString(resultVO)).info();
			return resultVO;
		}

		String customManagerWorkNum = selectCustomManagerWorkNum(prjBscInfoVO);
		if (StringUtils.isEmpty(customManagerWorkNum)) {
			resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
			resultVO.setInfo("未找到该项目的客户经理工号!");
			BaseLogUtils.newLogger("产品明细id:{},合格证管理的点击保存,未找到该项目的客户经理工号,{}",dtlId,JSON.toJSONString(resultVO)).info();
			return resultVO;
		}

		try {
			// 友好提示信息
			List<String> hintMsgList = new ArrayList<>();

			List<PrjPrdDtlGpsVO> gpsOneList = prjPrdDtlGpsService.gpsIsExist(prjPrdDtlVO.getId(), 1);
			BaseLogUtils.newLogger("产品明细id:{},gps序号1,前端的gps卡号:{},从库里查询的数据:{}",dtlId,gps11,CollectionUtils.isNotEmpty(gpsOneList) ? JSON.toJSONString(gpsOneList) : "空集合").info();

			if (CollectionUtils.isNotEmpty(gpsOneList)) {
				PrjPrdDtlGpsVO prjPrdDtlGpsVO = gpsOneList.get(0);

				if (!Objects.equals(prjPrdDtlGpsVO.getGpsCardNo(),gps11)) {
					String isUsedGpsOne = gpsDeviceIsUsed(projectId, gps1, dtlId, 1);
					if (StringUtils.isNotBlank(isUsedGpsOne)) {
						if (Objects.equals("1", isUsedGpsOne)) {
							// 未占用
							queryGpsDeviceInfoOfHadoop(projectId, customManagerWorkNum, gps1, 1,hintMsgList);
						} else {
							throw new BaseException(gps1 + ",已经占用,请核查!");
						}
					}
				}
			} else {
				String isUsedGpsOne = gpsDeviceIsUsed(projectId, gps1, dtlId, 1);
				if (StringUtils.isNotBlank(isUsedGpsOne)) {
					if (Objects.equals("1", isUsedGpsOne)) {
						// 未占用
						queryGpsDeviceInfoOfHadoop(projectId, customManagerWorkNum, gps1, 1,hintMsgList);
					} else {
						throw new BaseException(gps1 + ",已经占用,请核查!");
					}
				}
			}

			List<PrjPrdDtlGpsVO> gpsSecondList = prjPrdDtlGpsService.gpsIsExist(prjPrdDtlVO.getId(), 2);
			BaseLogUtils.newLogger("产品明细id:{},gps序号2,前端的gps卡号:{},从库里查询的数据:{}",dtlId,gps22,CollectionUtils.isNotEmpty(gpsSecondList) ? JSON.toJSONString(gpsSecondList) : "空集合").info();

			if (CollectionUtils.isNotEmpty(gpsSecondList)) {
				PrjPrdDtlGpsVO prjPrdDtlGpsVO = gpsSecondList.get(0);

				if (!Objects.equals(prjPrdDtlGpsVO.getGpsCardNo(),gps22)) {
					String isUsedGpsSecond = gpsDeviceIsUsed(projectId, gps2, dtlId, 2);
					if (StringUtils.isNotBlank(isUsedGpsSecond)) {
						if (Objects.equals("1", isUsedGpsSecond)) {
							// 未占用
							queryGpsDeviceInfoOfHadoop(projectId, customManagerWorkNum, gps2, 2,hintMsgList);
						} else {
							throw new BaseException(gps2 + ",已经占用,请核查!");
						}
					}
				}

			} else {
				String isUsedGpsSecond = gpsDeviceIsUsed(projectId, gps2, dtlId, 2);
				if (StringUtils.isNotBlank(isUsedGpsSecond)) {
					if (Objects.equals("1", isUsedGpsSecond)) {
						// 未占用
						queryGpsDeviceInfoOfHadoop(projectId, customManagerWorkNum, gps2, 2,hintMsgList);
					} else {
						throw new BaseException(gps2 + ",已经占用,请核查!");
					}
				}
			}


			List<PrjPrdDtlGpsVO> gpsThreeList = prjPrdDtlGpsService.gpsIsExist(prjPrdDtlVO.getId(), 3);
			BaseLogUtils.newLogger("产品明细id:{},gps序号3,前端的gps卡号:{},从库里查询的数据:{}",dtlId,gps33,CollectionUtils.isNotEmpty(gpsThreeList) ? JSON.toJSONString(gpsThreeList) : "空集合").info();

			if (CollectionUtils.isNotEmpty(gpsThreeList)) {
				PrjPrdDtlGpsVO prjPrdDtlGpsVO = gpsThreeList.get(0);

				if (!Objects.equals(prjPrdDtlGpsVO.getGpsCardNo(),gps33)) {
					String isUsedGpsThree = gpsDeviceIsUsed(projectId, gps3, dtlId, 3);
					if (StringUtils.isNotBlank(isUsedGpsThree)) {
						if (Objects.equals("1", isUsedGpsThree)) {
							// 未占用
							queryGpsDeviceInfoOfHadoop(projectId, customManagerWorkNum, gps3, 3,hintMsgList);
						} else {
							throw new BaseException(gps3 + ",已经占用,请核查!");
						}
					}
				}
			} else {
				String isUsedGpsThree = gpsDeviceIsUsed(projectId, gps3, dtlId, 3);
				if (StringUtils.isNotBlank(isUsedGpsThree)) {
					if (Objects.equals("1", isUsedGpsThree)) {
						// 未占用
						queryGpsDeviceInfoOfHadoop(projectId, customManagerWorkNum, gps3, 3,hintMsgList);
					} else {
						throw new BaseException(gps3 + ",已经占用,请核查!");
					}
				}
			}


			BaseLogUtils.newLogger("产品明细id:{},合格证页面保存的时候错误信息:hintMsgList:{}",dtlId,hintMsgList.toString()).info();
			if (CollectionUtils.isNotEmpty(hintMsgList)) {
				resultVO.setSuccess(BaseConstant.IS_YESNO_YES);
				resultVO.setInfo(hintMsgList.toString());
				return resultVO;
			}


		} catch (BaseException e) {
			BaseLogUtils.info(logger, "validateGps", "产品明细id:" + dtlId + ",合格证页面保存的时候校验异常:",e);
			resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
			resultVO.setInfo(e.getMessage());
		} catch (Exception e) {
			BaseLogUtils.info(logger, "validateGps", "产品明细id:" + dtlId + ",合格证页面保存的时候校验异常:",e);
			resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
			resultVO.setInfo(e.getMessage());
		}

		return resultVO;
	}

	/**
	 * @description gps设备是否使用
	 * @param prjId 项目id
	 * @param gpsCardNo gps卡号
	 * @param dtlId 产品明细id
	 * @param serialNo gps序号
	 * @return 0:占用 1:未占用 2:数据错误
	 */
	private String gpsDeviceIsUsed(Long prjId,String gpsCardNo, String dtlId,Integer serialNo) {
		ResponseData isUsedObj = null;
		if (StringUtils.isNotBlank(gpsCardNo) && !Objects.equals("0", gpsCardNo)) {
			 isUsedObj = prjPrdDtlGpsApiService.isUsed(gpsCardNo, Long.valueOf(dtlId));
			BaseLogUtils.newLogger("项目id:{},合格证页面点击保存,产品明细id:{},gps序号:{},是否使用:{}",prjId,dtlId,serialNo,null != isUsedObj ? JSON.toJSONString(isUsedObj) : "错误").info();
		}
		return  null != isUsedObj && isUsedObj.isSuccess()? (String) isUsedObj.getData() : "";
	}


	/**
	 * @description 查询GPS设备信息,调用大数据返回的数据
	 * @param prjId 项目id
	 * @param customManagerWorkNum 客户经理工号
	 * @param gpsCardNo gps卡号
	 * @param serialNo gps序号
	 * @param hintMsgList 提示信息
	 */
	private void queryGpsDeviceInfoOfHadoop(Long prjId, String customManagerWorkNum, String gpsCardNo, Integer serialNo,List<String> hintMsgList) {

		ResponseData responseData = prjPrdDtlGpsApiService.validateGpsDeviceOfHadoop((StringUtils.isNotBlank(gpsCardNo) ? gpsCardNo.trim() : "0"), customManagerWorkNum);

		BaseLogUtils.newLogger("项目id:{},GPS序号:{},调用大数据平台返回的数据:{}",prjId,serialNo,null == responseData ? "错误" :JSON.toJSONString(responseData)).info();

		hadoopReturnInfo(responseData,(StringUtils.isNotBlank(gpsCardNo) ? gpsCardNo.trim() : "0"), customManagerWorkNum,prjId,hintMsgList,serialNo);
	}

	/**
	 * @description 大数据返回的信息
	 * @param responseData 大数据返回的信息
	 * @param gpsCardNo gps卡号
	 * @param customManagerWorkNum 客户经理工号
	 * @param prjId 项目id
	 * @param hintMsgList 提示信息
	 * @param serialNo gps序号
	 */
	private void hadoopReturnInfo(ResponseData responseData,String gpsCardNo,String customManagerWorkNum,Long prjId,List<String> hintMsgList,Integer serialNo) {

		if (null != responseData) {
			if (!responseData.isSuccess()) {
				if ("hy4013".equals(responseData.getCode())) {
					// 报单人事业部下未查询到该设备
					throw new BaseException(gpsCardNo + "未查询到GPS设备，请核查!");

				} else if ("hy425".equals(responseData.getCode())) {
					//报单人账号在 GPS 系统暂无组织架构
					throw new BaseException(gpsCardNo + "GPS平台未查到当前客户经理信息，请核查!");

				} else {
					// 其他错误
					throw new BaseException(gpsCardNo + responseData.getMessage());
				}
			} else {

				PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(Long.valueOf(prjId));
				if (null == prjBscInfoVO) {
					throw new BaseException("项目id:" + prjId +",gps卡号:"+ gpsCardNo + ",未找到项目基本信息!");
				}

				// 客户经理名称
				String cstMgrNm = prjBscInfoVO.getCstMgrNm();
				BaseLogUtils.newLogger("项目id:{},查询出来的客户经理名称:{}",prjBscInfoVO.getId(),StringUtils.isNotBlank(cstMgrNm) ? cstMgrNm :"无").info();

				GpsDeviceDTO gpsDeviceDTO = (GpsDeviceDTO) responseData.getData();
				String workNum = gpsDeviceDTO.getReceiveName();
				BaseLogUtils.newLogger("项目id:{},调用大数据返回的GPS设备领用人工号:{}",prjId,StringUtils.isNotBlank(workNum) ? workNum :"无").info();

				String receiveRealName = gpsDeviceDTO.getReceiveRealName();
				BaseLogUtils.newLogger("项目id:{},调用大数据返回GPS设备领用人姓名:{}",prjId,StringUtils.isNotBlank(receiveRealName) ? receiveRealName :"无").info();

				// 没有领用人名字、工号,不弹框
				if (StringUtils.isNotBlank(receiveRealName)) {
					if (!Objects.equals(workNum,customManagerWorkNum)) {
						hintMsgList.add(gpsCardNo + ",GPS设备领用人【"+ receiveRealName +"】与实际使用人【"+ cstMgrNm +"】不一致，是否继续安装？");
					}
				}

			}

		} else {
			throw new BaseException("项目id:" + prjId +",gps卡号:"+ gpsCardNo + "，调用大数据返回空");
		}
	}

    /**
     * 如果该合格证对应的项目为城配业务  判断该项目流程的流程状态  若流程initList.do已发起 新增合格证信息的时候  设置合格证的状态、GPS状态为审核中
     * @param dtlId
     * @return
     */
	private Integer getCpSts(Long dtlId){
        int cpSts = BaseConstant.IS_YESNO_NO;
        PrjPrdDtlVO dtl = this.prjPrdDtlService.selectById(dtlId);
        if(dtl!=null){
            Long prjId = dtl.getPrjId();
            if(prjId!=null){
                PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(prjId);
                String prjTypCd = prjBscInfoVO.getPrjTypCd();
                if (StringUtils.isNotBlank(prjTypCd) && prjTypCd.equals(PrjBscInfoConstant.PRJ_TYP_CD_CPYW)){
                    String prjStsCd = prjBscInfoVO.getPrjStsCd();
                    if(prjStsCd.equals(FlowConstant.FLOW_CHECK_STATE_IN)
                            ||prjStsCd.equals(FlowConstant.FLOW_CHECK_STATE_SUBMIT)
                            ||prjStsCd.equals(FlowConstant.FLOW_CHECK_STATE_KNOW)){
                        cpSts = BaseConstant.IS_YESNO_YES;
                    }
                }
            }
        }else{
            throw new BaseException("未找到该合格证对应的项目产品明细信息");
        }
        return cpSts;
    }
	/**
	 * 验证GPS卡号是否存在,并添加GPS信息
	 * @param gpsNums
	 * @param dtlId
	 */
	private void saveGPS(String gpsNums, String dtlId,PrjBscInfoVO prjBscInfoVO) throws BaseException{
		// 验证GPS卡号是否存在,并添加GPS信息
		List<String> gpsNumsList = new ArrayList<String>();// 保存GPS记录用
		if (StringUtils.isNotBlank(gpsNums)){
			String[] gpsNumsArray = gpsNums.split(",");
			if (gpsNumsArray.length > 0){
				for (int i = 0; i<gpsNumsArray.length; i++){
					gpsNumsList.add(gpsNumsArray[i]);
				}

				// GPS卡号必须维护3个，如果不够，默认0
				if (gpsNumsList.size() == 1){
					gpsNumsList.add("0");
					gpsNumsList.add("0");
				} else if (gpsNumsList.size() == 2){
					gpsNumsList.add("0");
				}
			}
		} else {
			// GPS卡号必须维护3个，如果不够，默认0
			gpsNumsList.add("0");
			gpsNumsList.add("0");
			gpsNumsList.add("0");
		}

		BaseLogUtils.info(logger, "add", "GPS卡号信息:" + JSONObject.toJSONString(gpsNumsList), CurrentThreadContext.getCurrentUserName());
		// 添加GPS卡号信息,GPS数据存储到PRJ_PRD_DTL_GPS，不再往PRJ_PRD_DTL表中存
		//saveGPSInfo(gpsNumsList, dtlId);
		this.saveGPSInfoOfNewRules(gpsNumsList, dtlId,prjBscInfoVO);
	}

	/**
	 * 验证GPS卡号是否已存在
	 * @param gpsNum GPS卡号
	 */
	private void checkGPSExist(String gpsNum) {
		if (StringUtils.isNotBlank(gpsNum)) {
			PrjPrdDtlGpsQueryCondition qc = new PrjPrdDtlGpsQueryCondition();
			qc.setGpsCardNo(gpsNum);
			List<PrjPrdDtlGpsVO> list = this.prjPrdDtlGpsService.searchList(qc);
			if (null != list && list.size() > 0) {
				throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_200, "GPS卡号: " + gpsNum + " 已存在！");
			}
		}
	}

	/**
	 * 保存GPS信息
	 * @param gpsNums GPS卡号
	 */
	private void saveGPSInfo(List<String> gpsNums, String dtlId){
		List<PrjPrdDtlGpsVO> voList = new ArrayList<>();
		//如果该合格证对应的项目为城配业务  判断该项目流程的流程状态  若流程initList.do已发起 新增合格证信息的时候  设置合格证的状态、GPS状态为审核中
		int cpSts = this.getCpSts(Long.valueOf(dtlId));
		for (int i = 0; i< gpsNums.size(); i++){
			String gpsNum = gpsNums.get(i);
			DataResultDTO dto = this.prjPrdVehInfoService.getGPSInfo(gpsNum);
			JSONObject obj = (JSONObject) JSONObject.toJSON(dto.getData());
			BaseLogUtils.info(logger, "saveGPSInfo", "查询GPS第三方返回的信息:" + JSONObject.toJSONString(obj), CurrentThreadContext.getCurrentUserName());

			List<PrjPrdDtlGpsVO> gpsVOList = this.prjPrdDtlGpsService.gpsIsExist(Long.valueOf(dtlId), i+1);
			if (gpsVOList != null && gpsVOList.size() > 0){
				PrjPrdDtlGpsVO vo = gpsVOList.get(0);
				vo.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				vo.setMdfTm(new Date());
				vo.setGpsCardNo(gpsNum);
				vo.setUseTypCd(obj.getString("useType"));// 领用状态 0.未领用 1.已领用
                if(cpSts == BaseConstant.IS_YESNO_YES){
                    vo.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);// 审核状态 0.未审核 1.审核中 2.已审核 3.审核不通过
                }
				vo.setGpsStsCd(obj.getString("isExist"));// GPS平台状态 0.参数错误 1.设备不存在 2.设备正常 3.设备无位置信息,4：设备未入库
				vo.setGpsAddrInfo(obj.getString("address"));// 中文位置信息
				vo.setLat(obj.getString("lat"));// 纬度（保留两位小数）
				vo.setLng(obj.getString("lng"));// 经度（保留两位小数）
				vo.setOnlineType(obj.getString("onlineType"));

				this.prjPrdDtlGpsService.modify(vo);
			}else {
				PrjPrdDtlGpsVO gpsVO = new PrjPrdDtlGpsVO();
				gpsVO.setPrjDtlId(Long.valueOf(dtlId));
				gpsVO.setGpsCardNo(gpsNum);
				gpsVO.setUseTypCd(obj.getString("useType"));// 领用状态 0.未领用 1.已领用
				gpsVO.setSerialNo(i+1);
                if(cpSts == BaseConstant.IS_YESNO_YES){
                    gpsVO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);// 审核状态 0.未审核 1.审核中 2.已审核 3.审核不通过
                }else{
                    gpsVO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_NON);// 审核状态 0.未审核 1.审核中 2.已审核 3.审核不通过
                }
				gpsVO.setGpsStsCd(obj.getString("isExist"));// GPS平台状态 0.参数错误 1.设备不存在 2.设备正常 3.设备无位置信息,4：设备未入库
				gpsVO.setIsDel(0);//是否删除（1：是，0：否）
				gpsVO.setGpsAddrInfo(obj.getString("address"));// 中文位置信息
				gpsVO.setLat(obj.getString("lat"));// 纬度（保留两位小数）
				gpsVO.setLng(obj.getString("lng"));// 经度（保留两位小数）
				gpsVO.setOnlineType(obj.getString("onlineType"));
				gpsVO.setCrtTm(new Date());// 创建时间
				gpsVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());// 创建人

				prjPrdDtlGpsService.add(gpsVO);
			}
		}
	}

	/**
	 * 修订版（先删除再新增）
	 * @param gpsNums GPS卡号
	 */
	private void saveGPSInfoOfNewRules(List<String> gpsNums, String dtlId,PrjBscInfoVO prjBscInfoVO) throws BaseException{
		List<PrjPrdDtlGpsVO> voList = new ArrayList<>();
		//如果该合格证对应的项目为城配业务  判断该项目流程的流程状态  若流程initList.do已发起 新增合格证信息的时候  设置合格证的状态、GPS状态为审核中
		int cpSts = this.getCpSts(Long.valueOf(dtlId));
		for (int i = 0; i< gpsNums.size(); i++){
			String gpsNum = gpsNums.get(i);
			DataResultDTO dto = this.prjPrdVehInfoService.getGPSInfo(gpsNum);
			JSONObject obj = (JSONObject) JSONObject.toJSON(dto.getData());
			BaseLogUtils.info(logger, "saveGPSInfoOfNewRules", "新.查询GPS第三方返回的信息:" + JSONObject.toJSONString(obj), CurrentThreadContext.getCurrentUserName());

			String customManagerWorkNum = selectCustomManagerWorkNum(prjBscInfoVO);
			BaseLogUtils.newLogger("项目id:{}，gps卡号:{},当前客户经理工号:{}",prjBscInfoVO.getId(),gpsNum,StringUtils.isNotBlank(customManagerWorkNum) ? customManagerWorkNum :"无").info();

			List<PrjPrdDtlGpsVO> gpsVOList = this.prjPrdDtlGpsService.gpsIsExist(Long.valueOf(dtlId), i+1);
			PrjPrdDtlGpsVO newVo = new PrjPrdDtlGpsVO();
			newVo.setPrjDtlId(Long.valueOf(dtlId));
			newVo.setGpsCardNo(gpsNum);
			newVo.setSerialNo(i+1);
			newVo.setIsDel(0);//是否删除（1：是，0：否）
			if(null!=obj){
				newVo.setUseTypCd(obj.getString("useType"));// 领用状态 0.未领用 1.已领用
				newVo.setGpsStsCd(obj.getString("isExist"));// GPS平台状态 0.参数错误 1.设备不存在 2.设备正常 3.设备无位置信息,4：设备未入库
				newVo.setGpsAddrInfo(obj.getString("address"));// 中文位置信息
				newVo.setLat(obj.getString("lat"));// 纬度（保留两位小数）
				newVo.setLng(obj.getString("lng"));// 经度（保留两位小数）
				newVo.setOnlineType(obj.getString("onlineType"));
			}

			// 调用大数据返回新gps卡号的实际领用人、实际领用人工号、设备类型
			changeGpsInfo(prjBscInfoVO, gpsNum, customManagerWorkNum,newVo,dtlId);

			newVo.setCrtTm(new Date());// 创建时间
			newVo.setCrtUsrId(CurrentThreadContext.getCurrentUserId());// 创建人
			if (gpsVOList != null && gpsVOList.size() > 0){
				PrjPrdDtlGpsVO vo = gpsVOList.get(0);
				Long applyId = vo.getApplyId();//申请ID
				String audStsCd = vo.getAudStsCd();//审核状态
				if(cpSts == BaseConstant.IS_YESNO_YES){
					newVo.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);// 审核状态 0.未审核 1.审核中 2.已审核 3.审核不通过
				}else{
					newVo.setAudStsCd(audStsCd);// 审核状态 0.未审核 1.审核中 2.已审核 3.审核不通过
				}
				newVo.setApplyId(applyId);
				voList.add(newVo);
			}else {
				if(cpSts == BaseConstant.IS_YESNO_YES){
					newVo.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);// 审核状态 0.未审核 1.审核中 2.已审核 3.审核不通过
				}else{
					newVo.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_NON);// 审核状态 0.未审核 1.审核中 2.已审核 3.审核不通过
				}
				voList.add(newVo);
			}
		}
		this.prjPrdDtlGpsService.batchInsertWithDel(voList);
	}

	/**
	 * 测试获取GPS平台信息
	 * http://localhost:8083/project/prjprdvehinfo/getGps.do?gpsNum=6543245
	 * @param gpsNum
	 * @return
	 */
	@RequestMapping(value = "/getGps.do", method = { RequestMethod.GET })
	@ResponseBody
	public Object getGPS(@RequestParam("gpsNum") String gpsNum,@RequestParam("dtlId") Long dtlId){

		BaseLogUtils.newLogger("获取GPS设备位置信息入参，gpsNum={},dtlId={}",gpsNum,dtlId).info();
		DataResultVO result = null;
		try{
			if(StringUtils.isBlank(gpsNum) || "0".equals(gpsNum)){
				result =  new DataResultVO(BaseConstant.IS_YESNO_NO, "gpsNum为空");
				return result;
			}
			PrjPrdDtlVO dtlVO = this.prjPrdDtlService.selectById(dtlId);
			if(dtlVO == null || dtlVO.getPrjId() == null){
				result =  new DataResultVO(BaseConstant.IS_YESNO_NO, "未查询到产品信息");
				return result;
			}
			PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(dtlVO.getPrjId());
			if(prjBscInfoVO == null || prjBscInfoVO.getCstMgrId() == null){
				result =  new DataResultVO(BaseConstant.IS_YESNO_NO, "未查询到项目或项目经理");
				return result;
			}
			/*// 专车客车未接入大数据
			String cstMgrOrgCd = prjBscInfoVO.getCstMgrOrgCd();
			if(StringUtils.isBlank(cstMgrOrgCd) || cstMgrOrgCd.startsWith("000000080002")){
				result =  new DataResultVO(BaseConstant.IS_YESNO_NO, "未查询到客户经理组织机构或客户经理事业部无GPS数据");
				return result;
			}*/
			GpsAddressVO vo = this.prjPrdDtlGpsService.getGpsAddress(prjBscInfoVO.getCstMgrId(),gpsNum,"1");
			result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
			result.setData(vo);
		}catch(BaseException e){
			result = new DataResultVO(BaseConstant.IS_YESNO_NO, e.getMessage());
			BaseLogUtils.newLogger("获取GPS设备位置信息数据异常" ).error(LogExceptionEnum.API_CODE_0102,e);
		}catch (Exception e){
			result = new DataResultVO(BaseConstant.IS_YESNO_NO, e.getMessage());
			BaseLogUtils.newLogger("获取GPS设备位置信息数据异常" ).error(LogExceptionEnum.API_CODE_0102,e);
		}
		BaseLogUtils.newLogger("获取GPS设备位置信息返回={}",JSON.toJSONString(result)).info();
		return  result;

	}

	private PrjPrdVehInfoVO getRequestParams(HttpServletRequest request) {
		PrjPrdVehInfoVO vehInfo = new PrjPrdVehInfoVO();
		String certNo = request.getParameter("certNo");//合格证号
		String certDt = request.getParameter("certDt");//发证日期
		String mfrNm = request.getParameter("mfrNm");// 厂商名称
		String vehBr = request.getParameter("vehBr");//品牌
		String vehNm = request.getParameter("vehNm");//车辆名称
		String prdMdl = request.getParameter("prdMdl");//车辆型号
		String vin = request.getParameter("vin");//车架号
		String carCl  = request.getParameter("carCl");//车身颜色
		String chsMdl = request.getParameter("chsMdl");//底盘型号
		String chsId = request.getParameter("chsId");//底盘ID
		String chsCertNo = request.getParameter("chsCertNo");//底盘合格证编号
		String engMdl = request.getParameter("engMdl");//发动机型号
		String engNo = request.getParameter("engNo");//发动机号
		String fuelTyp = request.getParameter("fuelTyp");//燃料种类
		String outVol = request.getParameter("outVol");//排量（ml）
		String maxKw = request.getParameter("maxKw");// 功率（kW）
		String emiStd = request.getParameter("emiStd");//排放标准
		String oilCns = request.getParameter("oilCns");//油耗
		String outlineSz = request.getParameter("outlineSz");//外廓尺寸（mm）
		String cntrSz = request.getParameter("cntrSz");//货厢内部尺寸（mm）
		String leafSprNum = request.getParameter("leafSprNum");// 钢板弹簧片数（片）
		String whlNum = request.getParameter("whlNum");//轮胎数
		String whlSpec = request.getParameter("whlSpec");//轮胎规格
		String thread = request.getParameter("thread");//轮距(前/后)（mm）
		String whlBase = request.getParameter("whlBase");//轴距（mm）
		String axleLoad = request.getParameter("axleLoad");//轴荷（kg）
		String axisNum = request.getParameter("axisNum");//轴数
		String strTyp = request.getParameter("strTyp");// 转向形式
		String totWgt = request.getParameter("totWgt");// TOT_WGT
		String curbWgt = request.getParameter("curbWgt");// 整备质量（kg）
		String ratedWgt = request.getParameter("ratedWgt");// 额定载质量（kg）
		String wgtCoe = request.getParameter("wgtCoe");//载质量利用系数
		String traTotWgt = request.getParameter("traTotWgt");//准牵引总质量（kg）
		String semiMaxWgt = request.getParameter("semiMaxWgt");//半挂车鞍座最大允许总质量（kg）
		String cabSeatQty = request.getParameter("cabSeatQty");//驾驶室准乘人数（人）
		String ratedSeatQty = request.getParameter("ratedSeatQty");//额定载客（人）
		String maxSpd = request.getParameter("maxSpd");// 最高设计车速（km/h）
		String proDt = request.getParameter("proDt");//车辆制造日期
		String dtlRem = request.getParameter("dtlRem");//备注
		String dtlId = request.getParameter("dtlId");//产品明细ID
		String fileParams = request.getParameter("fileParams");//文件资料
		String gpsCardNo = request.getParameter("gpsCardNo");//gps1
		String gpsCardNo2 = request.getParameter("gpsCardNo2");//gps2
		String lnkCompId = request.getParameter("lnkCompId");//挂靠公司ID
		String lnkCompNm = request.getParameter("lnkCompNm");//挂靠公司名称
		String vinValidRes = request.getParameter("vinValidRes");//VIN验证结果

		if(StringUtils.isNotBlank(certDt)){
			vehInfo.setCertDt(DateUtils.formatStringToDate(certDt, DateUtils.YYYY_MM_DD));
		}
		if(StringUtils.isBlank(certNo)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"合格证编号不能为空！");
		}
		vehInfo.setCertNo(certNo);
/*		if(StringUtils.isBlank(vinNo)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"车架号不能为空！");
		}
*/		if(StringUtils.isNotBlank(lnkCompId)){
			vehInfo.setLnkCompId(Long.valueOf(lnkCompId));
		}
		if(StringUtils.isNotBlank(lnkCompNm)){
			vehInfo.setLnkCompNm(lnkCompNm);
		}
		vehInfo.setMfrNm(mfrNm);
		vehInfo.setGpsCardNo(gpsCardNo);
		vehInfo.setGpsCardNo2(gpsCardNo2);
		vehInfo.setPrdMdl(prdMdl);
		vehInfo.setVin(vin);
		vehInfo.setVehBr(vehBr);
		vehInfo.setVehNm(vehNm);
		vehInfo.setCarCl(carCl);
		vehInfo.setChsMdl(chsMdl);
		vehInfo.setChsId(chsId);
		vehInfo.setChsCertNo(chsCertNo);
		vehInfo.setFuelTyp(fuelTyp);
		vehInfo.setAxisNum(axisNum);
		vehInfo.setAxleLoad(axleLoad);
		vehInfo.setOutVol(outVol);
		vehInfo.setFuelTyp(fuelTyp);
		vehInfo.setMaxKw(maxKw);
		vehInfo.setEmiStd(emiStd);
		vehInfo.setOilCns(oilCns);
		vehInfo.setOutlineSz(outlineSz);
		vehInfo.setLeafSprNum(leafSprNum);
		vehInfo.setWhlNum(whlNum);
		vehInfo.setWhlSpec(whlSpec);
		vehInfo.setThread(thread);
		vehInfo.setWhlBase(whlBase);
		vehInfo.setStrTyp(strTyp);
		vehInfo.setCurbWgt(curbWgt);
		vehInfo.setRatedWgt(ratedWgt);
		if(StringUtils.isNotBlank(wgtCoe)){
			vehInfo.setWgtCoe(Double.valueOf(wgtCoe));
		}
		vehInfo.setTraTotWgt(traTotWgt);
		vehInfo.setSemiMaxWgt(semiMaxWgt);
		vehInfo.setCabSeatQty(cabSeatQty);
		vehInfo.setRatedSeatQty(ratedSeatQty);
		if(StringUtils.isNotBlank(maxSpd)){
			vehInfo.setMaxSpd(Double.valueOf(maxSpd));
		}
		if(StringUtils.isNotBlank(proDt)){
			vehInfo.setProDt(DateUtils.formatStringToDate(proDt, DateUtils.YYYY_MM_DD));
		}

		/*if(StringUtils.isBlank(machNo)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"整机号不能为空！");
		}*/
		if(StringUtils.isBlank(engMdl)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"发动机型号不能为空！");
		}
		vehInfo.setEngMdl(engMdl);
		/*if(StringUtils.isBlank(engNo)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_600,"发动机号/许可证号不能为空！");
		}*/
		vehInfo.setEngNo(engNo);
		List<SysUlFilesRecVO> fileList = new ArrayList<SysUlFilesRecVO>();
		if (StringUtils.isNotBlank(fileParams)) {
			fileList = JSON.parseArray(fileParams, SysUlFilesRecVO.class);
		}
		if(CollectionUtils.isNotEmpty(fileList)){
			for (SysUlFilesRecVO sysUlFilesRecVO : fileList) {
				sysUlFilesRecVO.setAbsLocPath(PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH)+sysUlFilesRecVO.getFilePath());
			}
			vehInfo.setFileList(fileList);
		}
		vehInfo.setDtlRem(dtlRem);
		vehInfo.setCntrSz(cntrSz);
		vehInfo.setTotWgt(totWgt);
		if(StringUtils.isNotBlank(certDt)){
			vehInfo.setCertDt(DateUtils.formatStringToDate(certDt, DateUtils.YYYY_MM_DD));
		}
		if(StringUtils.isNotBlank(dtlId)){
			vehInfo.setDtlId(Long.valueOf(dtlId));
		}
		vehInfo.setMdfTm(new Date());
		vehInfo.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		if(StringUtils.isNotBlank(vinValidRes)){
			vehInfo.setVinValidRes(vinValidRes);
		}
		return vehInfo;
	}



	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		PrjPrdVehInfoVO entity = null;
		try {
			entity = new PrjPrdVehInfoVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.prjPrdVehInfoService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	/**
	 * 到添加合格证照片列表页面
	 */
	@RequestMapping(value = "/addPrjPrdImgPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView addPrjPrdImgPage(HttpServletRequest request, HttpServletResponse response) {
		logger.info("到添加考察照片列表页面.");
		String dtlId = request.getParameter("dtlId");
		String sysCd = request.getParameter("sysCd");
		String orgCd = request.getParameter("orgCd");
		String cfgCd = request.getParameter("cfgCd");
		String cfgDtlCd = request.getParameter("cfgDtlCd");
		ModelAndView view = new ModelAndView("project/prjprdvehinfo/prjPrdVehImgPage");
		view.addObject("dtlId", dtlId);
		view.addObject("sysCd", sysCd);
		view.addObject("orgCd", orgCd);
		view.addObject("cfgCd", cfgCd);
		view.addObject("cfgDtlCd", cfgDtlCd);
		return view;
	}

	/**
	 * 到合格证照片列表页面
	 */
	@RequestMapping(value = "/prjPrdImgListPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView prjPrdImgListPage(HttpServletRequest request, HttpServletResponse response) {
		logger.info("到添加考察照片列表页面.");
		String dtlId = request.getParameter("dtlId");
		//查找上传的合格证照片信息
		String orgCd = PrjBscInfoConstant.CODE_PRJ_FILE_DEF_ORG;
		//查询项目的事业部
		PrjPrdDtlVO dtl = this.prjPrdDtlService.selectById(Long.valueOf(dtlId));
		if(null!=dtl){
			PrjBscInfoVO prjBsc = 	this.prjBscInfoService.selectById(dtl.getPrjId());
			if(null!=prjBsc){
				orgCd = prjBsc.getBuOrgCd();
			}
		}
		SysUlFilesRecQueryCondition fileQc = new SysUlFilesRecQueryCondition();
		fileQc.setCfgCd(PrjPrdBscInfoConstant.PRJ_PRD_FILE_CFG_CODE);
		fileQc.setCfgDtlCd(PrjPrdBscInfoConstant.PRJ_PRD_FILE_VEH_PHOTO_CODE);
		fileQc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		fileQc.setOrgCd(orgCd);
		fileQc.setPkId(dtlId);
		fileQc.setTabNm(PrjPrdBscInfoConstant.PRJ_PRD_FILE_VEH_PHOTO_TABLE_NM);
		List<SysUlFilesRecVO> list = this.sysUlFilesRecService.searchList(fileQc);
		String serverPath = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_SERVER_PATH);//服务地址
		String customerPah = PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_COSTOMER_PATH);
		String headPic = PropertiesCacheUtils.getProperty(fl.constant.facade.framework.constant.UploadConstant.DEFAULT_NO_PIC);
		ModelAndView view = new ModelAndView("project/prjprdvehinfo/prjPrdVehListImgPage");
		view.addObject("dtlId", dtlId);
		view.addObject("list", list);
		view.addObject("defImg", serverPath+customerPah+headPic);
		return view;
	}


	/**
	 * 新增考察/家访照片信息
	 */
	@RequestMapping(value = "/addProjectPhoto.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addProjectPhoto(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		String fileNm = request.getParameter("fileNm");
		String filePath = request.getParameter("filePath");
		String sysCd = request.getParameter("sysCd");
		String orgCd = request.getParameter("orgCd");
		String cfgCd = request.getParameter("cfgCd");
		String cfgDtlCd = request.getParameter("cfgDtlCd");
		String   fileParams = request.getParameter("fileList");
		String dtlId = request.getParameter("dtlId");
		Long id = null;
		List<SysUlFilesRecVO> fileList = new ArrayList<SysUlFilesRecVO>();
		if (StringUtils.isNotBlank(fileParams)) {
			fileList = JSON.parseArray(fileParams, SysUlFilesRecVO.class);
		}
		if(CollectionUtils.isNotEmpty(fileList)){
			for (SysUlFilesRecVO sysUlFilesRecVO : fileList) {
				sysUlFilesRecVO.setTabNm("PRJ_PRD_DTL");
				sysUlFilesRecVO.setCrtTm(new Date());
				sysUlFilesRecVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				sysUlFilesRecVO.setMdfTm(new Date());
				sysUlFilesRecVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				sysUlFilesRecVO.setIsDel(BaseConstant.IS_YESNO_NO);
				sysUlFilesRecVO.setAbsLocPath(PropertiesCacheUtils.getProperty(UploadConstant.UPLOAD_ROOT_PATH)+sysUlFilesRecVO.getFilePath());

			}
		}
		try {
			SysUlFilesRecVO fileRec = new SysUlFilesRecVO();

			SysUlFilesRecQueryCondition fileQc = new SysUlFilesRecQueryCondition();
			fileQc.setCfgCd(cfgCd);
			fileQc.setPkId(dtlId);
			fileQc.setTabNm("PRJ_PRD_DTL");
			fileQc.setOrgCd(orgCd);
			fileQc.setSysCd(sysCd);
			fileQc.setCfgDtlCd(cfgDtlCd);
		/*fileRec.setFileNm(fileNm);
		fileRec.setFilePath(filePath);
		fileRec.setSysCd(sysCd);
		fileRec.setOrgCd(orgCd);
		fileRec.setCfgCd(cfgCd);
		fileRec.setCfgDtlCd(cfgDtlCd);
		fileRec.setTabNm("PRJ_PRD_DTL");
		fileRec.setCrtTm(new Date());
		fileRec.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
		fileRec.setMdfTm(new Date());
		fileRec.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		fileRec.setIsDel(BaseConstant.IS_YESNO_NO);*/
			this.prjBscInfoService.addFileRecList(fileQc,fileList);
			//查询保存成功的数据
		/*SysUlFilesRecVO filesRecVO = 	this.sysUlFilesRecService.selectById(id);
		result.setData(filesRecVO);*/
			result.setData(fileList.get(0));
			BaseLogUtils.info(logger, "add", "新增数据.[id="+id+"] DATA:" + JSONObject.toJSONString(fileParams), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(fileParams) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(fileParams) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 获取合格证照片列表
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getPrjPrdVehImgList.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object getPrjPrdVehImgList(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String dtlId = request.getParameter("dtlId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);


		try {

			String orgCd = PrjBscInfoConstant.CODE_PRJ_FILE_DEF_ORG;
			//查询项目的事业部
//			PrjPrdDtlVO dtl = this.prjPrdDtlService.selectById(Long.valueOf(dtlId));
//			if(null!=dtl){
//				PrjBscInfoVO prjBsc = 	this.prjBscInfoService.selectById(dtl.getPrjId());
//				if(null!=prjBsc){
//					orgCd = prjBsc.getBuOrgCd();
//				}
//			}
			//查找上传的合格证照片信息
			SysUlFilesRecQueryCondition fileQc = new SysUlFilesRecQueryCondition();
			fileQc.setCfgCd(PrjPrdBscInfoConstant.PRJ_PRD_FILE_CFG_CODE);
			if (StringUtils.isNotBlank(request.getParameter("cfgDtlCd"))) {
				fileQc.setCfgDtlCd(request.getParameter("cfgDtlCd"));
			}
			fileQc.setSysCd(CurrentThreadContext.getCurrentSysCd());
			//fileQc.setOrgCd(orgCd);
			fileQc.setPkId(dtlId);
			fileQc.setTabNm(PrjPrdBscInfoConstant.PRJ_PRD_FILE_VEH_PHOTO_TABLE_NM);
			List<SysUlFilesRecVO> list = this.sysUlFilesRecService.searchList(fileQc);

			//排序最小的在前面
			if (list!=null) {
				//如果配置是空筛选出合格证跟其他
				if (!StringUtils.isNotBlank(request.getParameter("cfgDtlCd"))) {
					for (int i = 0; i < list.size(); i++) {
						if (PrjPrdBscInfoConstant.PRJ_PRD_FILE_VEH_PHOTO_CODE.equals(list.get(i).getCfgDtlCd())
								||PrjPrdBscInfoConstant.PRJ_PRD_FILE_VEH_PHOTO_QT_CODE.equals(list.get(i).getCfgDtlCd())								) {

						}else {
							list.remove(i);
							i--;
						}
					}
				}
				int n=0;
				for (int i = 0; i < list.size(); i++) {
						if (list.get(n).getId()>list.get(i).getId()) {
							n=i;
						}
				}
				List<SysUlFilesRecVO> list2=new ArrayList<SysUlFilesRecVO>();
				list2.add(list.get(n));
				for (int i = 0; i < list.size(); i++) {
					if (i!=n) {
						list2.add(list.get(i));
					}
				}
				list=list2;
			}
			result.setData(list);
			BaseLogUtils.info(logger, "getPrjPrdVehImgList", "解析数据失败!", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getPrjPrdVehImgList", "获取失败.[id=]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getPrjPrdVehImgList", "获取失败.[id=]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 到选择挂靠公司列表页面
	 */
	@RequestMapping(value = "/toChooseLnkCompPage.do", method = { RequestMethod.GET})
	public ModelAndView toChooseLnkCompPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("project/prjprdvehinfo/prdLnkCompListPage");
		BaseLogUtils.info(logger, "toListPage", "跳转到选择挂靠公司列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到准时放款流程合格证列表页签
	 * @param request
	 * @param response
	 * @param isGpsNode 是否为风控审批GPS 节点 1：是 0：否
	 * @return
	 */
	@RequestMapping(value = "/toPrjPrdVehInfoListInFlow.do", method = { RequestMethod.GET})
	public ModelAndView toPrjPrdVehInfoListInFlow(HttpServletRequest request, HttpServletResponse response,@RequestParam(required = false,defaultValue = "0") String isGpsNode){
		ModelAndView view = new ModelAndView("project/prjprdvehinfo/prjPrdVehInfoListInFlow");
		String paySchNo = request.getParameter("paySchNo");//支付表号
		String isAuditNode = request.getParameter("isAuditNode");//是否可修改 1：是
		String isAllowPay = request.getParameter("isAllowPay");//是否可修改 1：是
		// 展示挂靠公司更改/移除按钮
		String noLinkAction = request.getParameter("noLinkAction");
		view.addObject("noLinkAction", noLinkAction);
		view.addObject("paySchNo",paySchNo);
		view.addObject("isAuditNode",isAuditNode);
		view.addObject("isGpsNode",isGpsNode);
		view.addObject("isAllowPay",isAllowPay);
		BaseLogUtils.info(logger, "toPrjPrdVehInfoListInFlow", "跳转到准时放款流程合格证列表页签.", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	/**
	 * 初始化准时放款流程合格证列表数据
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initPrjPrdVehInfoListInFlow.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initPrjPrdVehInfoListInFlow(HttpServletRequest request, HttpServletResponse response) {

		String paySchNo = request.getParameter("paySchNo");

		PrjPrdVehInfoQueryCondition qc = new PrjPrdVehInfoQueryCondition();

		if (StringUtils.isNotEmpty(paySchNo)) {
			qc.setPaySchNo(paySchNo);
		}else{
			return null;
		}
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());
		qc.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
		qc.setCfgCd(PrjBscInfoConstant.CODE_PRJ_PRD_FILE_CD);
		qc.setCfgDtlCd(PrjPrdBscInfoConstant.PRJ_PRD_FILE_VEH_PHOTO_CODE);
		qc.setUsrId(CurrentThreadContext.getCurrentUserId());

		Pager page = new Pager();
		page.setCurrentPage(1);
		page.setEveryPage(10);
		page.setCondition(qc);

		Pager pager = this.prjPrdVehInfoService.searchListPage(page);
		List<PrjPrdVehInfoVO> list = (List<PrjPrdVehInfoVO>) pager.getResultList();
		ListPageVO<PrjPrdVehInfoVO> listPage = new ListPageVO<PrjPrdVehInfoVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initPrjPrdVehInfoListInFlow", "查询数据完成. DATA:" + JSONObject.toJSONString(list), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 验证是否能变更GPS
	 * /project/prjprdvehinfo/checkCanStartFlow.do
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/checkCanStartFlow.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object checkCanStartFlow(HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
		result.put("code", "1");//表示可以发起流程
		String id = request.getParameter("dtlId");//项目产品明细id
		//DataResultVO result = new DataResultVO(BaseConsta`nt.IS_YESNO_NO);
		if(StringUtils.isEmpty(id)){
			result.put("code", "0");
			result.put("info", "项目产品明细id不能为空");
			return result;
		}

		//根据id去查询付款信息表
		try {
			CapPayInfoQueryCondition condition = new CapPayInfoQueryCondition();
			condition.setPrjPrdDtlId(Long.parseLong(id));
			condition.setIsDel(0);
			BaseLogUtils.info(logger, "searchCapPayInfoList", "条件查询付款信息表请求参数是"+JSON.toJSONString(condition));
			List<CapPayInfoDTO> searchCapPayeeInfoList = ICapPayeeInfoApiService.searchCapPayInfoList(condition);
			BaseLogUtils.info(logger, "searchCapPayInfoList", "条件查询付款信息表返回结果是"+JSON.toJSONString(searchCapPayeeInfoList));

			if(CollectionUtils.isEmpty(searchCapPayeeInfoList)|| searchCapPayeeInfoList.size()>2){
				result.put("info", "项目产品明细id不能为空");
				return result;
			}

			CapPayInfoDTO dto = searchCapPayeeInfoList.get(0);
			//获取放款状态
			String payStsCd = dto.getPayStsCd();

			if(StringUtils.isEmpty(payStsCd) || !(payStsCd.equals("3")||payStsCd.equals("5"))){
				result.put("code", "0");
				result.put("info", "未放款的产品不能发起GPS变更");
				return result;
			}

		} catch (Exception e) {
			result.put("code", "2");
			result.put("info", e.getMessage());
		}
		return result;
	}

	@RequestMapping(value = "/addStartFlow.do", method = { RequestMethod.POST})
	@ResponseBody
	public Object addStartFlow(HttpServletRequest request, HttpServletResponse response) {
		String gpsNew1 = request.getParameter("gps1");//gps卡1
		String gpsNew2 = request.getParameter("gps2");//gps卡2
		String gpsNew3 = request.getParameter("gps3");//gps卡2
		String id = request.getParameter("dtlId");//项目产品明细id
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_NO);


		if(StringUtils.isEmpty(id)){
			result.setInfo("项目产品明细id不能为空");
			return result;
		}


		// 根据id去查询付款信息表
		try {
			CapPayInfoQueryCondition condition = new CapPayInfoQueryCondition();
			condition.setPrjPrdDtlId(Long.parseLong(id));
			condition.setIsDel(0);
			BaseLogUtils.info(logger, "searchCapPayInfoList", "条件查询付款信息表请求参数是" + JSON.toJSONString(condition));
			List<CapPayInfoDTO> searchCapPayeeInfoList = ICapPayeeInfoApiService.searchCapPayInfoList(condition);
			BaseLogUtils.info(logger, "searchCapPayInfoList",
					"条件查询付款信息表返回结果是" + JSON.toJSONString(searchCapPayeeInfoList));

			if (CollectionUtils.isEmpty(searchCapPayeeInfoList) || searchCapPayeeInfoList.size() > 2) {
				result.setInfo("付款信息表数据有误dtlId" + id);
				return result;
			}

			CapPayInfoDTO dto = searchCapPayeeInfoList.get(0);
			// 获取放款状态
			String payStsCd = dto.getPayStsCd();

			if (StringUtils.isEmpty(payStsCd) || !(payStsCd.equals("3") || payStsCd.equals("5"))) {
				result.setInfo("未放款的产品不能发起GPS变更");
				return result;
			}

		} catch (Exception e) {

			result.setInfo(e.getMessage());
			return result;
		}


		if(StringUtils.isEmpty(gpsNew1) && StringUtils.isEmpty(gpsNew2)){
			result.setInfo("GPS不能同时为空");
			return result;
		}

		//获取GPS卡号信息
		PrjPrdDtlGpsQueryCondition condition = new PrjPrdDtlGpsQueryCondition();
		condition.setIsDel(0);
		condition.setPrjDtlId(Long.parseLong(id));
		BaseLogUtils.info(logger, "searchList", "查询GPS信息表请求参数是"+JSON.toJSONString(condition));
		List<PrjPrdDtlGpsVO> searchList = prjPrdDtlGpsService.searchList(condition);
		BaseLogUtils.info(logger, "searchList", "查询GPS信息表返回结果是"+JSON.toJSONString(searchList));



		if(CollectionUtils.isEmpty(searchList)){
			result.setInfo("GPS信息数据有误:PrjDtlId"+id);
			return result;
		}
		//组装新GPS信息
		List<String> newGps = new ArrayList<>(3);
		if(StringUtils.isNotEmpty(gpsNew1)){
			newGps.add(gpsNew1);
		}

		if(StringUtils.isNotEmpty(gpsNew2)){
			newGps.add(gpsNew2);
		}

		if(StringUtils.isNotEmpty(gpsNew3)){
			newGps.add(gpsNew3);
		}
		//获取老GPS卡信息
		/*String gpsOld1 = null;
		String gpsOld2 = null;*/
		List<String> oldGps = new ArrayList<>(3);

		for (PrjPrdDtlGpsVO dto : searchList) {
			if(StringUtils.isNotEmpty(dto.getGpsCardNo())){
				oldGps.add(dto.getGpsCardNo());
			}

		}

		boolean bool = false; //bool 是否发起流程标识 true标识发起流程 false 标识不发起流程



		int flag = 0;

		for (String nGps:newGps){
			if ("0".equals(nGps)) {
				continue;
			}
			for (String oGps:oldGps){
				if ("0".equals(oGps)) {
					continue;
				}
				if(nGps.equals(oGps)){
					flag++;
					break;
				}
			}
		}
		if (flag < oldGps.size()){
			bool = true;
		}

		//判断填写数据是否有重复
		List checkList = new ArrayList();
		for(String gpsCardNo:newGps){
			if(StringUtils.isNotBlank(gpsCardNo) && !gpsCardNo.equals(BaseConstant.IS_YESNO_NO_STR)){
				if(checkList.contains(gpsCardNo)){
					result.setInfo("填写的GPS重复，请调整!");
					return result;
				}
				checkList.add(gpsCardNo);
			}
		}

		for (String nGps:newGps){
			Integer ret = prjPrdDtlGpsService.checkGPSExist(nGps, Long.parseLong(id));

			if(ret!=1){ // 0表示占用 1表示未占用 2 数据错误
				result.setInfo("修改的GPS信息被其他资产占用,请调整");
				return result;
			}
		}

		PrjPrdDtlVO prjPrdDtlVO = this.prjPrdDtlService.selectById(Long.valueOf(id));
		PrjBscInfoVO prjBscInfoVO = this.prjBscInfoService.selectById(prjPrdDtlVO.getPrjId());
		String customManagerWorkNum = selectCustomManagerWorkNum(prjBscInfoVO);

		if(bool){
			try{
				//0.添加数据
				PrjPrdGpsApplyDTO entity = new PrjPrdGpsApplyDTO();
				entity.setCrtTm(new Date());
				entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				entity.setIsDel(0);
				entity.setCstMgrNm(CurrentThreadContext.getCurrentUserName());
				entity.setCstMgrId(CurrentThreadContext.getCurrentUserId());
				entity.setCstMgrOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
				entity.setPrjPrdDtlId(Long.parseLong(id));

				BaseLogUtils.info(logger, "addPrjPrdGpsApplyDTO", "添加GPS申请表请求参数是"+JSON.toJSONString(entity));

				Long applyId = prjPrdGpsApplyApiService.addPrjPrdGpsApplyDTO(entity);
				BaseLogUtils.info(logger, "addPrjPrdGpsApplyDTO", "添加GPS申请表返回结果是"+JSON.toJSONString(applyId));



				//1.发起GPS变更流程
				PrjFlowUserInfoQC param = new PrjFlowUserInfoQC();
				param.setId(applyId);
				param.setCurrentBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
				param.setCurrentOrgCd(CurrentThreadContext.getCurrentOrgCd());
				param.setCurrentOrgDispNm(CurrentThreadContext.getCurrentOrgDispNm());
				param.setCurrentSysCd(CurrentThreadContext.getCurrentSysCd());
				param.setCurrentUserId(CurrentThreadContext.getCurrentUserId());
				param.setCurrentUserName(CurrentThreadContext.getCurrentUserName());
				DataResultDTO addFlowStart = prjPrdGpsApplyApiService.addFlowStart(param);
				if(addFlowStart.getCode().equals("1")){
					//流程发起成功后 修改GPS信息
					for (PrjPrdDtlGpsVO prjPrdDtlGpsDTO : searchList) {
						prjPrdDtlGpsDTO.setApplyId(applyId);
						if(prjPrdDtlGpsDTO.getSerialNo().toString().equals("1")){
							prjPrdDtlGpsDTO.setGpsCardNo(gpsNew1);
							// 调用大数据返回新gps卡号的实际领用人、实际领用人工号、设备类型
							changeGpsInfo(prjBscInfoVO, gpsNew1, customManagerWorkNum,prjPrdDtlGpsDTO,id);

						}
						if(prjPrdDtlGpsDTO.getSerialNo().toString().equals("2")){
							prjPrdDtlGpsDTO.setGpsCardNo(gpsNew2);
							// 调用大数据返回新gps卡号的实际领用人、实际领用人工号、设备类型
							changeGpsInfo(prjBscInfoVO, gpsNew2, customManagerWorkNum,prjPrdDtlGpsDTO,id);
						}

						if(prjPrdDtlGpsDTO.getSerialNo().toString().equals("3")){
							prjPrdDtlGpsDTO.setGpsCardNo(gpsNew3);
							// 调用大数据返回新gps卡号的实际领用人、实际领用人工号、设备类型
							changeGpsInfo(prjBscInfoVO, gpsNew3, customManagerWorkNum,prjPrdDtlGpsDTO,id);
						}
						prjPrdDtlGpsDTO.setAudStsCd("1");//审核中
					}
					BaseLogUtils.info(logger, "modifyPrjPrdDtlGpsList", "修改gps信息表请求参数是"+JSON.toJSONString(searchList));
					boolean modifyPrjPrdDtlGpsList = prjPrdDtlGpsService.modifyPrjPrdDtlGpsList(searchList);
					BaseLogUtils.info(logger, "modifyPrjPrdDtlGpsList", "修改gps信息表返回结果是"+JSON.toJSONString(modifyPrjPrdDtlGpsList));
					result.setSuccess(1);
					result.setInfo("发起变更流程操作成功");
				}else{
					result.setInfo(addFlowStart.getInfo());
				}
			}catch (Exception e){
				BaseLogUtils.info(logger, "modifyPrjPrdDtlGpsList", "修改gps信息表请求参数是"+JSON.toJSONString(e.getMessage()));

			}


		}else{
			result.setInfo("GPS信息没有改变,没有发起变更流程");
		}
		BaseLogUtils.newLogger("GPS变更流程实时发送设备信息开始入参dtlId=" + id).info();
		boolean b = deviceInfoApiService.sendDeviceInfo(Long.valueOf(id));
		BaseLogUtils.newLogger("GPS变更流程实时发送设备信息返回结果dtlId=" + id + "b=" + b).info();
		return result;
	}

	@Autowired
	private IPrjPrdGpsApplyApiService prjPrdGpsApplyApiService;


	@Autowired
	private ICapPayInfoApiService ICapPayeeInfoApiService;

	@RequestMapping(value = "/updateGpsInfo.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object updateGpsInfo(HttpServletRequest request, HttpServletResponse response) {
		JSONObject result = new JSONObject();
		String currentPage = request.getParameter("page");//当前页
		Pager page = new Pager();
		PrjPrdDtlGpsQueryCondition condition = new PrjPrdDtlGpsQueryCondition();
		condition.setIsDel(0);
		page.setCondition(condition);
		page.setEveryPage(100);
		if(StringUtils.isEmpty(currentPage)){
			result.put("page", "page字段不能为空"+JSON.toJSONString(currentPage));
			return result;
		}
		page.setCurrentPage(Integer.parseInt(currentPage));
		BaseLogUtils.info(logger, "searchListPage", "分页查询GPS信息请求参数是"+JSON.toJSONString(page));
		Pager searchListPage = prjPrdDtlGpsService.searchListPage(page);
		BaseLogUtils.info(logger, "searchListPage", "分页查询GPS信息返回结果是"+JSON.toJSONString(searchListPage));


		List<PrjPrdDtlGpsVO>  gpsList = (List<PrjPrdDtlGpsVO>) searchListPage.getResultList();

		if(CollectionUtils.isEmpty(gpsList)){
			result.put("gpsList", "数据为空"+JSON.toJSONString(page));
			return result;
		}

		int failNum = 0;
		StringBuffer sb = new StringBuffer();
		for (PrjPrdDtlGpsVO dto : gpsList) {
			String gpsCardNo = dto.getGpsCardNo();
			if(StringUtils.isEmpty(gpsCardNo)){
				failNum ++;
				sb.append(dto.getId().toString());
				sb.append(",");
				continue;
			}
			DataResultDTO gpsInfo = prjPrdVehInfoService.getGPSInfo(gpsCardNo);
			if(gpsInfo.getCode().equals("0")){
				sb.append(dto.getId().toString());
				sb.append(",");
				continue;
			}
			net.sf.json.JSONObject jsonObject = (net.sf.json.JSONObject) gpsInfo.getData();
			dto.setGpsStsCd(jsonObject.get("isExist").toString());//获取请求状态
			dto.setGpsAddrInfo(jsonObject.get("address").toString());//位置信息
			dto.setLng(jsonObject.get("lng").toString());//经度
			dto.setLat(jsonObject.get("lat").toString());//维度
			dto.setUseTypCd(jsonObject.get("useType").toString());//设备状态
			dto.setOnlineType(jsonObject.get("onlineType").toString());// 在线状态

		}
		BaseLogUtils.info(logger, "batchPrjPrdDtlGpsList", "批量修改GPS信息请求参数是"+JSON.toJSONString(gpsList));
		prjPrdDtlGpsService.modifyPrjPrdDtlGpsList(gpsList);


		result.put("failNum", failNum);
		result.put("failIds", sb);
		return result;
	}
	/**
	 * 合格证ocr识别
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/ocrVeh.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object ocrVeh(HttpServletRequest request, HttpServletResponse response) {
		String url = request.getParameter("url");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "识别成功");
		if(StringUtils.isEmpty(url)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "ocrVeh", "获取数据,主键不存在.[id="+url+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}

		try {
			InvoiceOrCertQueryCondition con=new InvoiceOrCertQueryCondition();
			con.setType(InvoiceOrCertQueryCondition.TYPE_CERTIFICATE);
			con.setImgPath(url);
			CheckInvoiceResultDTO dto=this.checkInvoiceApiService.getInvoiceOrCertByOCR(con);

			if(null == dto){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "ocrVeh", "获取数据,数据不存在.[url="+url+"]", CurrentThreadContext.getCurrentUserName());
			}else if(!dto.getSuccess()){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("识别失败");
				BaseLogUtils.info(logger, "ocrVeh", "获取数据,数据错误.[url="+url+"]", CurrentThreadContext.getCurrentUserName());
			}

			result.setData(dto);
			BaseLogUtils.info(logger, "ocrVeh", "获取数据.[data="+JSONUtils.valueToString(dto.getPrjPrdVehInfoDTO())+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "ocrVeh", "获取失败.[url="+url+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "ocrVeh", "获取失败.[url="+url+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 根据车牌号获取中交GPS信息
	 */
	@RequestMapping(value = "/getChinaGPSInfo.do", method = {RequestMethod.GET})
	@ResponseBody
	public Object getChinaGPSInfo(HttpServletRequest request, HttpServletResponse response) {
		String dtlId = request.getParameter("dtlId");
		PrjPrdDtlGpsDTO gpsInfo = new PrjPrdDtlGpsDTO();
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		try {
			if (StringUtils.isNotBlank(dtlId)) {
                BaseLogUtils.info(logger, "getChinaGPSInfo", "prjPrdLicInfoService.selectById参数dtlId:" + dtlId, CurrentThreadContext.getCurrentUserName());
				PrjPrdLicInfoVO licInfo = prjPrdLicInfoService.selectById(Long.valueOf(dtlId));
				if (licInfo != null && StringUtils.isNotBlank(licInfo.getVehNo()) && FlowConstant.FLOW_CHECK_STATE_PASS.equals(licInfo.getAudStsCd())) {
                    gpsInfo = prjPrdVehInfoService.getChinaGPSInfo(licInfo.getVehNo());
					gpsInfo.setGpsCardNo(licInfo.getVehNo());//车牌号
				}
			}
			result.setData(gpsInfo);
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getChinaGPSInfo", "根据车牌号获取中交GPS信息失败:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.info(logger, "getChinaGPSInfo", "根据车牌号获取中交GPS信息失败:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 根据二维码获取合格证信息
	 */
	@RequestMapping(value = "/getVehInfoByQR.do", method = {RequestMethod.POST})
	@ResponseBody
	public Object getVehInfoByQR(@RequestParam("qrStr") String qrStr) {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_NO, "合格证解析失败");
		try {
			if (StringUtils.isNotBlank(qrStr)) {
				BaseLogUtils.info(logger, "getVehInfoByQR", "参数qrStr:" + qrStr, CurrentThreadContext.getCurrentUserName());
				String jsonStr = projectApiService.analyseVehInfo(qrStr);
				JSONObject jsonObject = JSONObject.parseObject(jsonStr);
				if(jsonObject != null && StringUtils.isNotBlank(jsonObject.getString("success"))){
					result.setSuccess(jsonObject.getIntValue("success"));
					result.setInfo(jsonObject.getString("msg"));
					PrjPrdVehInfoVO data = JSONObject.parseObject(jsonObject.getString("data"),PrjPrdVehInfoVO.class);
					result.setData(data);
				}
			}
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("合格证解析失败");
			BaseLogUtils.info(logger, "getVehInfoByQR", "解析二维码信息失败:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("合格证解析失败");
			BaseLogUtils.info(logger, "getVehInfoByQR", "解析二维码信息失败:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}


	@RequestMapping(value = "/validateGpsDeviceInfo.do", method = {RequestMethod.GET})
	@ResponseBody
	public Object validateGpsDeviceInfo(@RequestParam("gpsCardNo") String gpsCardNo,@RequestParam("dtlId") Long dtlId,@RequestParam(value = "prjId",required = false,defaultValue = "") String prjId){
		BaseLogUtils.newLogger("获取GPS设备信息入参，项目id:{},gps卡号:{},产品明细id:{}",prjId,gpsCardNo,dtlId).info();
		DataResultVO result = null;
		try{
			if(StringUtils.isBlank(gpsCardNo)){
				result =  new DataResultVO(BaseConstant.IS_YESNO_NO, "gps卡号为空");
				return result;
			}
			PrjPrdDtlVO dtlVO = this.prjPrdDtlService.selectById(dtlId);
			if(dtlVO == null){
				result =  new DataResultVO(BaseConstant.IS_YESNO_NO, "未查询到产品信息");
				return result;
			}

			PrjBscInfoVO prjBscInfoVO = null;
			if (StringUtils.isBlank(prjId)) {
			    prjBscInfoVO = this.prjBscInfoService.selectById(dtlVO.getPrjId());
			} else {
				 prjBscInfoVO = this.prjBscInfoService.selectById(Long.valueOf(prjId));
			}

			if(prjBscInfoVO == null || prjBscInfoVO.getCstMgrId() == null){
				result =  new DataResultVO(BaseConstant.IS_YESNO_NO, "未查询到项目或客户经理");
				return result;
			}

			String customManagerWorkNum = selectCustomManagerWorkNum(prjBscInfoVO);
			BaseLogUtils.newLogger("项目id:{}，gps卡号:{},当前客户经理工号:{}",prjBscInfoVO.getId(),gpsCardNo,StringUtils.isNotBlank(customManagerWorkNum) ? customManagerWorkNum :"无").info();

			ResponseData responseData = queryGpsDeviceInfoOfHadoop(prjBscInfoVO, gpsCardNo,customManagerWorkNum);
			if (null == responseData) {
				result =  new DataResultVO(BaseConstant.IS_YESNO_NO, "调用大数据查询GPS设备信息,返回空");
				return result;
			}

			// 调用大数据查询GPS设备信息，返回错误信息
			if (!responseData.isSuccess()) {
				if ("hy4013".equals(responseData.getCode())) {
					// 报单人事业部下未查询到该设备
					throw new BaseException("未查询到GPS设备，请核查!");

				} else if ("hy425".equals(responseData.getCode())) {
					//报单人账号在 GPS 系统暂无组织架构
					throw new BaseException("GPS平台未查到当前客户经理信息，请核查!");

				} else {
					// 其他错误
					throw new BaseException(responseData.getMessage());
				}
			} else {
				/*
				 * 调用大数据，返回正确信息
				 */
				result = new DataResultVO(BaseConstant.IS_YESNO_YES);
				GpsDeviceDTO gpsDeviceDTO = (GpsDeviceDTO) responseData.getData();
				BaseLogUtils.newLogger("项目id:{},gps卡号:{},大数据返回的正确信息:{}",prjBscInfoVO.getId(),gpsCardNo,null != gpsDeviceDTO ? JSON.toJSONString(gpsDeviceDTO) : "无数据").info();
				result.setData(gpsDeviceDTO);

			}

		}catch(BaseException e){
			result = new DataResultVO(BaseConstant.IS_YESNO_NO, e.getMessage());
			BaseLogUtils.newLogger("产品明细id:{}，校验GPS设备信息数据异常",dtlId).error(LogExceptionEnum.API_CODE_0102,e);
		}catch (Exception e){
			result = new DataResultVO(BaseConstant.IS_YESNO_NO, e.getMessage());
			BaseLogUtils.newLogger("产品明细id:{},校验GPS设备信息数据异常",dtlId).error(LogExceptionEnum.API_CODE_0102,e);
		}
		BaseLogUtils.newLogger("产品明细id:{},校验GPS设备信息返回={}",dtlId,JSON.toJSONString(result)).info();
		return  result;
	}


	/**
	 * @description 查询客户经理工号
	 * @param prjBscInfoVO 项目基本信息
	 */
	private String selectCustomManagerWorkNum(PrjBscInfoVO prjBscInfoVO) {
			List<Long> list = new ArrayList<>();

			// 客户经理id
			Long cstMgrId = prjBscInfoVO.getCstMgrId();
			list.add(cstMgrId);

			SysUsrQueryCondition sysUsrQueryCondition = new SysUsrQueryCondition();
			// 客户经理id
			sysUsrQueryCondition.setUsrIds(list);
			sysUsrQueryCondition.setSysCd("11000");

			List<SysUsrDTO> sysUsrDtoS = sysUsrApiService.searchSysUsrList(sysUsrQueryCondition);
			BaseLogUtils.newLogger("项目id:{},查询出来的系统用户:{}",prjBscInfoVO.getId(),JSON.toJSONString(sysUsrDtoS)).info();

			if (CollectionUtils.isNotEmpty(sysUsrDtoS)) {
				for (SysUsrDTO sysUsrDto : sysUsrDtoS) {
					if (null != sysUsrDto && null != sysUsrDto.getUsrNm()) {
						return  sysUsrDto.getUsrNm();
					}
				}
			}
		return null;
	}


	/**
	 * @description 查询GPS设备信息,调用大数据返回的数据
	 * @param prjBscInfoVO  项目基本信息
	 * @param gpsCardNo gps卡号信息
	 * @param customManagerWorkNum 当前客户经理工号
	 */
	private ResponseData queryGpsDeviceInfoOfHadoop(PrjBscInfoVO prjBscInfoVO, String gpsCardNo,String customManagerWorkNum) {
		ResponseData responseData = null;

		if (StringUtils.isNotBlank(customManagerWorkNum)) {
			responseData = prjPrdDtlGpsApiService.validateGpsDeviceOfHadoop((StringUtils.isNotBlank(gpsCardNo) ? gpsCardNo.trim() : "0"), customManagerWorkNum);
			BaseLogUtils.newLogger("项目id:{},GPS卡号:{},调用大数据平台返回的数据:{}",prjBscInfoVO.getId(),gpsCardNo,null == responseData ? "错误" :JSON.toJSONString(responseData)).info();
		}
		return  responseData;
	}


	/**
	 * @description 变更GPS卡号，同时要变更实际领用人、实际领用人工号、设备类型
	 * @param prjBscInfoVO 项目基本信息
	 * @param gpsCardNo 变更的gps卡号
	 * @param customManagerWorkNum 客户经理工号
	 * @param prjPrdDtlGpsVO gps model
	 * @param dtlId 项目产品明细id
	 */
	private void changeGpsInfo(PrjBscInfoVO prjBscInfoVO, String gpsCardNo, String customManagerWorkNum, PrjPrdDtlGpsVO prjPrdDtlGpsVO,String dtlId) {
		PrjPrdDtlGpsQueryCondition condition = new PrjPrdDtlGpsQueryCondition();
		condition.setGpsCardNo(gpsCardNo);
		condition.setPrjDtlId(Long.valueOf(dtlId));
		ResponseData isHaveGpsCardNoData = prjPrdDtlGpsApiService.selectList(condition);
		BaseLogUtils.newLogger("项目id:{},gps卡号:{},保存时从库里查询的数据:{}",prjBscInfoVO.getId(),gpsCardNo,JSON.toJSONString(isHaveGpsCardNoData)).info();

		if (isHaveGpsCardNoData.isSuccess()) {
			List<cn.fl.preloan.dto.PrjPrdDtlGpsDTO> list = (List<cn.fl.preloan.dto.PrjPrdDtlGpsDTO>) isHaveGpsCardNoData.getData();

			if (CollectionUtils.isEmpty(list)) {
				ResponseData responseData = queryGpsDeviceInfoOfHadoop(prjBscInfoVO, gpsCardNo, customManagerWorkNum);
				if (null != responseData  && null != responseData.getData()) {
					prjPrdDtlGpsVO.setReceiveRealName(((GpsDeviceDTO)responseData.getData()).getReceiveRealName());
					prjPrdDtlGpsVO.setReceiveName(((GpsDeviceDTO)responseData.getData()).getReceiveName());
					prjPrdDtlGpsVO.setGpsDeviceType(((GpsDeviceDTO)responseData.getData()).getGpsDeviceType());
				}
			} else {
				cn.fl.preloan.dto.PrjPrdDtlGpsDTO prjPrdDtlGpsVO1 = list.get(0);
				prjPrdDtlGpsVO.setReceiveRealName(prjPrdDtlGpsVO1.getReceiveRealName());
				prjPrdDtlGpsVO.setReceiveName(prjPrdDtlGpsVO1.getReceiveName());
				prjPrdDtlGpsVO.setGpsDeviceType(prjPrdDtlGpsVO1.getGpsDeviceType());
			}
		}
	}
}

